I have two activities: main activity and child activity.
When I press a button in the main activity, the child activity is launched.
Now I want to send some data back to the main screen. I used the Bundle class, but it is not working. It throws some runtime exceptions.
Is there any solution for this?
This example demonstrates how do I pass data between activities in android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.
Intent i = new Intent(this, SecondActivity. class); startActivityForResult(i, 1); In your SecondActivity set the data which you want to return back to FirstActivity. If you don't want to return back, don't set any.
We can send the data using putExtra() method from one activity and get the data from the second activity using the getStringExtra() method.
Declare A in your manifest with the android:launchMode="singleTask" . This way, when you call startActivity() from your other activies, and A is already running, it will just bring it to the front. Otherwise it'll launch a new instance.
There are a couple of ways to achieve what you want, depending on the circumstances.
The most common scenario (which is what yours sounds like) is when a child Activity is used to get user input - such as choosing a contact from a list or entering data in a dialog box. In this case you should use startActivityForResult
to launch your child Activity.
This provides a pipeline for sending data back to the main Activity using setResult
. The setResult method takes an int result value and an Intent that is passed back to the calling Activity.
Intent resultIntent = new Intent(); // TODO Add extras or a data URI to this intent as appropriate. resultIntent.putExtra("some_key", "String data"); setResult(Activity.RESULT_OK, resultIntent); finish();
To access the returned data in the calling Activity override onActivityResult
. The requestCode corresponds to the integer passed in in the startActivityForResult
call, while the resultCode and data Intent are returned from the child Activity.
@Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch(requestCode) { case (MY_CHILD_ACTIVITY) : { if (resultCode == Activity.RESULT_OK) { // TODO Extract the data returned from the child Activity. String returnValue = data.getStringExtra("some_key"); } break; } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With