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);
   startActivity(intent);
   }
  });

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:

@Override
     public void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         setContentView(R.layout.main2);
         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);
    finish();
        }

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.

@Override
    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.


23 Responses to “Android App Development: Using intents to pass data and return results between activities”

  1. mossila 14. Mar, 2011 at 3:11 am #

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

  2. Barina 05. May, 2011 at 5:14 am #

    awesome thanks :)

  3. Sandip 23. May, 2011 at 6:38 am #

    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 16. Jan, 2012 at 9:00 pm #

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

  4. Atiq 04. Jul, 2011 at 3:00 am #

    hi,
    it is really nice. thanx a lot.

  5. Henrik 26. Aug, 2011 at 6:04 am #

    Good tutorial.

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

    Do you know?

    • Vaibhav 16. Jan, 2012 at 9:01 pm #

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

  6. Bouheang 25. Oct, 2011 at 9:01 pm #

    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 11. Jun, 2012 at 9:29 am #

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

  7. Anonymous 24. Jan, 2012 at 10:12 am #

    you can give Double.parse.Double(a)

  8. Anonymous 20. Mar, 2012 at 12:25 am #

    thanks a ton.

  9. Akhil 20. Mar, 2012 at 12:28 am #

    Thanks a lot.

  10. Saraswati 10. May, 2012 at 4:06 am #

    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 (eg.name,address etc).

  11. Anonymous 25. Jun, 2012 at 2:10 am #

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

  12. yashas 03. Sep, 2012 at 3:57 am #

    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.

  13. Anonymous 20. Feb, 2013 at 7:11 am #

    u can use passing of strings by putextra methods

  14. M J 19. Jun, 2013 at 3:35 am #

    Really brilliant thanks

  15. Johny 28. Sep, 2013 at 3:22 am #

    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:
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
    try {

    mcam.setPreviewDisplay(holder);
    mcam.setPreviewCallback( new PreviewCallback() {

    @Override
    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) {
    cv.onConvert();
    Intent returnIntent = new Intent();
    returnIntent.putExtra(“return”, “ok”);
    setResult(RESULT_OK,returnIntent);
    mcam.setPreviewCallback(null);
    finish();
    } else {
    if (data!= null) {
    Log.i(“DATA LENGTH”, data.length+””);
    Integer[] rgb = new Integer[width*height];
    decodeYUV420SP(rgb, data, width, height);
    cv.LT.add(rgb);
    }
    }
    }
    });
    mcam.startPreview();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }
    Thanks anyways for help! :)

  16. doniwahyu 20. Jan, 2014 at 8:16 pm #

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

  17. Rayhon 19. Feb, 2014 at 7:50 pm #

    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.

  18. Arun 10. Mar, 2014 at 6:34 am #

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

Trackbacks/Pingbacks

  1. Android App Development: Using intents to pass data and return results between activities | Mobile Orchard | D.J. Lactose Productions - 04. Sep, 2012

    [...] and return results between activities | Mobile Orchard Posted on September 4, 2012 by Nick Android App Development: Using intents to pass data and return results between activities | Mobile O…. This entry was posted in Android, Development. Bookmark the permalink. ← Todd DeLand: [...]

  2. Passing data between fragments and the next activity : Android Community - For Application Development - 28. Feb, 2013

    [...] . Either way you have to pass data using Intents [...]

Leave a Reply



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