ANDROID – Pass data between 3 activities

Android applications are made up of one or more activities. And as you move from screen to screen in your app, you may need to share information between the various activities e.g the username, current score etc. This is easy enough when you are just passing information back and forth between two screens (activities), but needs a slight tweak if you need to pass data between more than 2 activities. For example, I earn 10 points on screen A, I click through to screen B to check my points balance to see if I have enough points to buy a new weapon? Yay, I do! So I click through to Screen C to buy a fancy new sword, which I would like to use back in Screen A.

This is easily achieved by forwarding your results.

And if we wanted to get the result from Activity C passed by to A, for the scenario I have described above. We would:

Code Snippet: Passing Data Between 3 Activities

Start Activity B from Activity A:

Intent showB = new Intent(ActivityA, ActivityB);
startActivityForResult(showB, RequestCode);

In Activity B call Activity C, but direct that the results be forwarded:

Intent showC = new Intent(ActivityC);
showC.setFlags(Intent.FLAG_ACTIVITY_FORWARD_RESULT);
startActivity(showC);
finish(); //Close Activity B

In Activity C, bundle up the result:

//set the result code and close the activity
Intent result = new Intent();
setResult(RequestCode, result);
finish();

In Activity A, handle the returned result:

public void onActivityResult(int requestCode, int resultCode, Intent data) {
//handle RequestCode here
}

 

Result: we successfully passed data between Activity A and Activity C.

If you’ve found this useful, please let me know by liking this post, Thanks!

And here are some useful links if you would like to learn more about activities and how Android handles communication/messaging:

1. http://developer.android.com/guide/components/activities.html

2. http://www.vogella.com/tutorials/AndroidIntent/article.html

 

 

Leave a Reply