In previous lesson Linking Activity  we learned how go to one activity to another using Intent. Now in this lesson we will work on passing data between Activities.

For a example, you would possibly want to launch another activity to gather some user-related information, so you pass the name of the user to another activity. once the user has finished collecting all the information, the information also needs to be passed back to the calling activity. Hence, you need to be able to pass information back and forth between activities. This example shows you how to do.

Solution Stuff :

You can make use of the Intent class to pass data to another activity. To pass primitive data types to another activity, you can use the putExtra() method, as the following code :

The preceding statements create an Intent object and then attach 2 values to that using the putExtra() method: one for a string and one for an integer.

When you start another activity using the Intent object, the data attached to the Intent object is passed to the destination activity. To call another activity with the intention of obtaining some data back from it, use the startActivityForResult() method:

The startActivityForResult() method takes an Intent object as well as a request code. The request code is an integer value that’s greater than or equal to zero. This request code is used to identify returning activities, as you will call over one activity at the same time.

If you set the request code to -1, then the call of startActivityForResult() is equivalent to startActivity(). That is, you’ll not be able to get data passed back from the destination activity.

On the target activity, to retrieve the data that was passed to it, you use the getIntent() method to get the instance of the Intent object that was passed to it. to get the simple data type passed in through the putExtra() method, use the getExtra() method, wherever the type is also String, int, float, and so on. the following code shows however the 2 primitive data types are retrieved:

Complete Code

1. Put this code in First Acitivty (MainActivity .xml)

2. Put this code in second Activity (SecondActivity.xml)

You see data in Toast (What is Toast click here)
Passing Data Between Activities in Android

Note : This example (Project) is developed in Eclipse Version Kepler, tested on Android 4.4.2 (KitKat Version) and SDK build-tools 22.6.3

Download Passing Data Between Activities Source code :


Leave a Reply