poursina
poursina

Reputation: 87

Pass an object between activities

I made an app that has three activities, and it works like this:

Activity A --> Activity B --> Activity C

and for returning from activity C to activity A is like this :

Activity C --> Activity B --> Activity A

and I wanna to pass an object in Activity C to Activity A, but when I press back button or what ever, all of activity's objects has destroyed,and I can't receive the object on Activity A .How can I pass an object in Activity C to Activity A?

(I used DB for solving this problem already and when I am in activity C , I insert the object in a table and also use the table in activity A for getting the object . But I am looking for easier way to solve it)

please guide me...

Thanks

Upvotes: 0

Views: 81

Answers (3)

coder
coder

Reputation: 13248

using shared Preferences in Activity C as shown.

SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
data.edit().putString("somevalue", myvalue).commit();

and calling it in Activity A as:

SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String myval= data.getString("somevalue",""); 

Upvotes: 1

tjurczyk
tjurczyk

Reputation: 111

If this is primitive data type, you can go with a SharedPreferences mechanism. You can also use some public static fields.

More information about your problem: http://developer.android.com/guide/faq/framework.html#3

Upvotes: 0

Sergi Pasoevi
Sergi Pasoevi

Reputation: 2851

You might override onActivityResult in your Activities A and B, so that B just takes the result back from the C and passes it back to A

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
  super.onActivityResult(requestCode, resultCode, data);
  switch(requestCode) {
     case (A) : {
      if (resultCode == Activity.RESULT_OK) {
        // Extract the data returned from the Activity.
      }
      break;
    } 
  }
}

while in B and C you should pass back the object to the calling activity:

Intent resultIntent = new Intent();
// add your object here to the resultIntent
setResult(Activity.RESULT_OK, resultIntent);
finish();

Upvotes: 1

Related Questions