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?
Sending Data Back
It helps me to see things in context. Here is a complete simple project for sending data back. Rather than providing the xml layout files, here is an image.
Main Activity
startActivityForResult
, providing it an arbitrary result code.onActivityResult
. This is called when the Second Activity finishes. You can make sure that it is actually the Second Activity by checking the request code. (This is useful when you are starting multiple different activities from the same main activity.)Intent
. The data is extracted using a key-value pair.MainActivity.java
Second Activity
Intent
. The data is stored in theIntent
using a key-value pair.RESULT_OK
and add the intent holding your data.finish()
to close the Second Activity.SecondActivity.java
Other notes
RESULT_OK
. Just use the full name:Activity.RESULT_OK
.See also
Use sharedPreferences and save your data and access it from anywhere in the application
save date like this
And recieve data like this
There are some ways of doing this. 1. by using the startActivityForResult() which is very well explained in the above answers.
by creating the static variables in your "Utils" class or any other class of your own. For example i want to pass studentId from ActivityB to ActivityA.First my ActivityA is calling the ActivityB. Then inside ActivityB set the studentId (which is a static field in Utils.class). Like this Utils.STUDENT_ID="1234"; then while comming back to the ActivityA use the studentId which is stored in Utils.STUDENT_ID.
by creating a getter and setter method in your Application Class.
like this:
so you are done . just set the data inside when u are in ActivityB and after comming back to ActivityA , get the data.
In first activity u can send intent using
startActivityForResultand()
and then get result from secound activity after it finished usingsetResult
.MainActivity.class
========= secound activity
Call the child activity Intent using the startActivityForResult() method call
There is an example of this here: http://developer.android.com/training/notepad/notepad-ex2.html
and in the "Returning a Result from a Screen" of this: http://developer.android.com/guide/faq/commontasks.html#opennewscreen
I have created simple demo class for your better reference.