Rami
Rami

Reputation: 2148

How to Pass object from sub activity to main activity?

From ActivityA I'm starting ActivityB.
In ActivityB I'm creating a new Serializable object.
After the object has been created I want to close ActivityB and pass the new object to ActivityA.

How can I do it?

Upvotes: 2

Views: 2004

Answers (4)

Chandra Sekhar
Chandra Sekhar

Reputation: 19492

after the object is created, create an intent object, put that object to that intent and then start activity A. In the Activity A's onRestart() get that intent and from that intent get that object.

Upvotes: 0

Sadeshkumar Periyasamy
Sadeshkumar Periyasamy

Reputation: 4908

Start the Activity B using startActivityForResult method.

When you finish creating object call setResult in Activity B. Set Your Data in Intent. You don't need to finish this.

Override function onActivityResult in Activity A. This will be called when you call setResult in Activity B. You can receive the data from Intent passed from Activity B.

But most of the time, you need separate Activities if only you have different screens with different tasks. Otherwise accomplish the task within the same Activity. *(A Good and Standard Practice).*

Upvotes: 2

Jave
Jave

Reputation: 31846

start Activity B with startActivityForResult().
In activity B, when the object is created create an Intent to pack the object in:

Intent result = new Intent();
result.putExtra("result", object);
setResult(RESULT_OK, result);

Then you will receive that intent in the onActivityResult() method of Activity A, where you can extract it like so:

data.getSerializableExtra("result");

Upvotes: 5

luciferche
luciferche

Reputation: 134

Why are you doing that? If you're using activity B only for creating new object, you can do it in a plain simple java class. What are you trying to accomplish?

Upvotes: -1

Related Questions