Android App Development: Using intents to pass data and return results between activities

In my previous tutorial I explained how intents describe an action to be performed. We learned how to launch phone activities like phone dialer with intents, and how we passed data (The phone number to dial) to the phone activity.

In this post I’m going to see show you how to use intents to launch several activities within the same application and how to pass data between them.

We will make an application with three activities, each activity has a button that when pressed navigates to the next activity in a round-robin fashion.
this is what each activity looks like:

Each button will navigate to the next activity like this:

btn1.setOnClickListener(new OnClickListener() {

   public void onClick(View v) {
    // TODO Auto-generated method stub
   Intent intent=new Intent(IntentsDemo2.this,Activity2.class);

and the same for each button in the other activities.

We created the intent with a constructor that takes two parameters:

  1. Context: a reference to the current activity.
  2. Class: the type of the activity to be launched by the intent.

Passing Results between Intents:

By default when you launch an activity using an intent you don’t have a feedback on the whether the launched activity finished it’s work or not.

We can launch an activity as a sub activity of a parent activity. This means that when the sub activity closes, it triggers an event handler in the parent.

Consider the previous example, we want each activity to display the name of the activity that was displayed before it. So we launch the intent normally but we use the Intent.putExtra(String Name,String Value) method to pass any extra data needed.

In the first activity we launch the second activity like this:

Intent intent=new Intent(IntentsDemo2.this,Activity2.class);
   intent.putExtra("ComingFrom", "Acticity 1");
final int result=1;
   startActivityForResult(intent, result);

We did not use the startActivity method as we did before, instead we used startActivityForResult(Intent intent, int requestCode)
thich takes two parameters:

  1. The intent to start.
  2. Request code: which is an integer identifier that is used as a corelation id to identify which sub activity has finished it’s work (will explain later) .

So the above code launches a sub activity and passes it an extra peice of information via Intent.putExtra method.

Receiving Extra data in sub activity:

Now the sub activity has been started with an intent from the parent with some extra data. to retreive this data in the sub activity we use the getIntent() method.

The getIntent() method returns a reference t the intent tha started the sub activity.

So in the sub activity we can call the method like this:

     public void onCreate(Bundle savedInstanceState) {
         Intent sender=getIntent();
         String extraData=sender.getExtras().getString("ComingFrom");

This retreives the extra data added to the intent in the parent activity.

Handling sub activity results:

Now suppose that the parent activity wants to know what was the result returned from the sub activity or wants to get some data from the sub activity, this is handled by overriding the onActivityResult method in the parent activity.

Now suppose that the sub activity wants to pass a string containg the word “Hello” to the parent activity.

In the sub activity there is a button that when pressed returns to the parent activity. The button’s click event handler can be like this:

btn.setOnClickListener(new OnClickListener() {

    public void onClick(View v) {
     // TODO Auto-generated method stub
    Intent intent=new Intent();
    intent.putExtra("ComingFrom", "Hello");
    setResult(RESULT_OK, intent);

Here we used the intent.putExtra method to pass the extra data.

we also used the setResult(int result,Intent intent) method to set a result code to be sent to the caller parent activity.
The result code often has two predefined values Result_OK or Result_CANCELED. you can define any result value you want.

Also we called finish() method that closes the activity and returrns to the caller activity.

When the finish() method is invoked in the sub activity, the onActivityResult callback method is invoked in the caller activity.

So when overriding the onActivityResult method in the caller activity we can get the data passed from the sub activity.

    public void onActivityResult(int requestCode,int resultCode,Intent data)
     super.onActivityResult(requestCode, resultCode, data);

     String extraData=data.getStringExtra("ComingFrom"));

This was how intents can be used to pass data and return results between several activities within the same applications. Stay tuned for more Android tutorials next week.

  • mossila

    How can activity 2 call activity3 then activity3 -> finish and return to activity 1?

  • Barina

    awesome thanks :)

  • Sandip

    hi , This is Good Example !!!!!!!
    But I want to Pass More than one value from one Activity to another Activity.
    How i do that.
    Please Send me Replay as soon as!!!!
    Thanks in Advanced !!!

    • Vaibhav

      You can pass number of values the same way and can get the number of values same way…!!

  • Atiq

    it is really nice. thanx a lot.

  • Henrik

    Good tutorial.

    How do you pass parameters between two separate apps?
    The above works within one app, I assume.

    Do you know?

    • Vaibhav

      For that your application should work as “Content Provider”..

  • Bouheang

    hi, every body

    i am new android dev, i have a problem that i can not input float number like:12.3232 in editText,
    this is my code in .xml

    How can i do if i want to input float number like 12.3232. Thank u for every body can give me some solution.

    • Anon

      Take the input as a String then convert it to a double with The static method Double.parseDouble(aString)

  • Anonymous

    you can give Double.parse.Double(a)

  • Anonymous

    thanks a ton.

  • Akhil

    Thanks a lot.

  • Saraswati

    Thanks for this tutorial. Can you please explain how to make the query results clickable? I have created a local database and got a cursor after querying it. I want to show these results as clickables and based on the click i want to show the contents of that result (,address etc).

  • Anonymous

    How can activity 2 call activity3 then activity3 -> finish and return to activity 1?

  • yashas

    where should be the function onActivityresult() function placed.Should it be placed in onClick(View v) function or outside it?
    If i place it outside it is not working…….Moreover the display of first activity is done but no control is moving to it.

  • Pingback: Android App Development: Using intents to pass data and return results between activities | Mobile Orchard | D.J. Lactose Productions

  • Anonymous

    u can use passing of strings by putextra methods

  • Pingback: Passing data between fragments and the next activity : Android Community - For Application Development

  • M J

    Really brilliant thanks

  • Johny

    I have called finish() method but the sub activity is not return. How can I force it return??

    This is my code from parent activity :
    Intent i = new Intent(Main.this, GetPic.class);
    startActivityForResult(i, 1);

    This is my code on sub activity:
    public void surfaceCreated(SurfaceHolder holder) {
    try {

    mcam.setPreviewCallback( new PreviewCallback() {

    public void onPreviewFrame(byte[] data, Camera cam) {
    Calendar n = Calendar.getInstance();
    if (((n.get(Calendar.MINUTE)-c.get(Calendar.MINUTE))*60 + n.get(Calendar.SECOND)-c.get(Calendar.SECOND))>10) {
    Intent returnIntent = new Intent();
    returnIntent.putExtra(“return”, “ok”);
    } else {
    if (data!= null) {
    Log.i(“DATA LENGTH”, data.length+””);
    Integer[] rgb = new Integer[width*height];
    decodeYUV420SP(rgb, data, width, height);
    } catch (IOException e) {
    Thanks anyways for help! :)

  • doniwahyu

    Thx bos ….. article very usefull …. :)

  • Rayhon

    I don’t see any arguments to finish(); so how does onActivityResult know about the new intent that was made in the closed activity and the data that was added to it.

  • Arun

    Can U please share me pass and return value from application to application ???

© 2008-2014 • Mobile Orchard and the Bar-Tree Logo are service marks. ContactAdvertise