Home > Android > android startActivity and startActivityForResult

android startActivity and startActivityForResult

In my previous tutorial I have talked a little bit about intent. So we have our intention to do something either explicitly or implicitly now it’s time to start those intent. And we do this via startActivity() or startActivityForResult() but why do we have two kind of method for this.

As name suggest startAcitvity will only take you there where you wanna go without worrying about getting any result from child activity to parent activity.
It’s real classic when you have a sequence activity to go through, like filling some information in every activity and that’s it.
What if you want an activity that uses information from other activity or may be other application. In that case you need more than just startActivity(). And that’s when comes startAcitvityForResult().
So it start another activity from your activity and it expect to get some data from child activity and return that to parent activity.
Let’s see some example:

final Bundle bundle = new Bundle();
al.add(1,un.getText().toString());
bundle.putStringArrayList("Q1", al);
Intent intent=new Intent(PageOne.this,PageTwo.class);
intent.putExtras(bundle);
startActivity(intent);

In this case I just wanna go from page one to page two and I don’t expect to get something from page two but I want page two to receive some data from page one and that I have sent using intent.putExtras().Full Code: ReportGenerator

Now we will try to understand startAcitvityForResult(). using previous ContactPicker example.
If you have not downloaded it yet you can download it from:
ContactPicker
At first we should be creating an intent in our main activity that is ContentPickerTester and also create a static integer variable
public static final int PICK_CONTACT=1;
now that need to be done bcz you don’t actually know which sub activity is going to give you the result(if you are using implicit intent) so we need to somehow differentiate between sub activities so that we can take different type of action for different type of result.
Intent intent=new Intent(Intent.ACTION_PICK,
Uri.parse("content://contacts/"));

startActivityForResult() accept two parameters as it’s arguments, one is going to be the explicit or implicit intent and another is called request code which is our static variable.
startActivityForResult(intent,PICK_CONTACT);
now whenever subactivity finishes, it will return the request code you have sent, along with the data and a result code to your main activity.

Let’s look at the subactivity (ContactPicker)
In the subactivity side subactivity will finish itself and return the data to the parent whenever it gets the chance to execute the below code.
Uri outUri=Uri.parse(data.toString()+rowId);
Intent outData=new Intent();
outData.setData(outUri);
setResult(Activity.RESULT_OK,outData);
finish();

Here Activity.RESULT_OK is the result code we were talking about. Now if something goes wrong with subactivity Activity.RESULT_CANCEL will return.

I don’t know if you have noticed or not that we are not calling ContactPicker anywhere in our main activity. Well we actually calling it implicitly. See at manifest file
That in our ContactPicker activity we have something like this:

<intent-filter>

<action android:name="android.intent.action.PICK"/>

<category android:name="android.intent.category.DEFAULT"/>

<data android:scheme="content" android:path="contacts"></data>

</intent-filter>

You should also remember that when we have created an intent in our main activity we defined our action as Intent.ACTION_PICK. And of course ContactPicker has an action named android.intent.action.PICK. And also the kind of data we are looking. Android will use something called Intent Resolution to find a best fit activity and that is in our case is ContactPicker activity.So voila, startActivityForResult() will open up ur subactivity.
After choosing a contact it will return to the main activity by setting the result setResult(Activity.RESULT_OK,outData) and finishing off the subactivity.

Now all you have to do is taking care of the returned data in the main activity and that is done by
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case(PICK_CONTACT):{
if(resultCode==Activity.RESULT_OK)
{
//blah blah…
}
break;
}
}
}

And that’s it. A real simple application. Awesome, isn’t it? And plz do comment or question , that will encourage me to write more. Also if there is any mistake let me know so that I can correct myself. And “HAVE A GOOD PROGRAMMING”

Categories: Android
  1. Aditya
    March 28, 2011 at 5:11 am

    Thanks,
    Really Helpful..

    • saiful103a
      March 28, 2011 at 8:36 pm

      Thanks bro. Need your feedback to improve.

  2. Max Waterman
    April 18, 2011 at 12:54 pm

    I have an activity that I want to use in two modes; in one case it will not return anything, but in the other it will.
    Should I use ‘startActivityForResult()’ in both modes using a ‘mode’ parameter and make the ‘result’ empty in the mode where there is nothing to return?
    Or is there some way to tell that it has been started with ‘..ForResult()’ or plain ‘startActivity()’?

    • saiful103a
      April 20, 2011 at 12:12 pm

      To return something to parent activity from child activity we must use startActivityForResult() even if it is null.But if we want to go to the next activity without caring about give something back to our previous activity we just use startActivity().And to give ur answer, yah u should use ‘startActivityForResult()’ in both modes using a ‘mode’ parameter bcz after all you have to return something or nothing. 🙂

  3. Ashish Kamath
    March 6, 2012 at 7:34 am

    I want 2 connect two XML files using a button..how do i do it ? Plz help

    • saiful103a
      March 11, 2012 at 11:01 am

      Your Q is not clear to me, are you trying to put two xml layout in one layout when some button pressed, for that you can use “merge” so multiple layout can work on one layout or you are talking about two raw xml file?Am not clear what you are trying to say.

  4. May 12, 2012 at 7:07 pm

    Helpful, thanks.

  5. June 24, 2012 at 12:53 pm

    A comprehensive note on the topic!

    • saiful103a
      June 24, 2012 at 3:19 pm

      Thanks,
      Hoping to write more.

      • June 25, 2012 at 6:43 pm

        that’s great, I will reblog it, dear saif!

  6. June 24, 2012 at 12:53 pm

    Reblogged this on Shafique Ur Rehman.

  7. saiful103a
    October 30, 2012 at 1:03 pm

    Hi Irving,
    Sorry for the trouble, i will try to modify my about me page to put my contact info in there.
    My email id: saiful103a at gmail dot com
    Thanks

  8. tishgomez1990
    August 26, 2013 at 10:19 pm

    Would you be fascinated by exchanging links?

  9. January 5, 2014 at 4:43 pm

    I haven’t checked in here for some time since
    I thought it was getting boring, but the

    last several posts are good quality so I guess I will add you back to
    my daily bloglist.

    You deserve it my friend 🙂

  10. June 15, 2014 at 9:31 am

    Check out the new viral game monkey king online with its released hack Monkey king online hack
    I just found a new awesome hack tool for my favourite game monkey king online
    Omg check this hack for monkey king online game its working like charm!

  11. September 1, 2014 at 1:35 am

    An intriguing discuesion iis definitely worth comment. I do believe that youu
    need to publish more on this subject matter, it mmay not be a taboo matter but usually people don’t talk about these issues.
    To the next! Cheers!!

  12. September 3, 2014 at 1:45 am

    Can I simply say what a relief tto discover someone who ruly nows what they’re talking about on the net.
    You certainly understand hhow to bring an issje to light and make it important.
    More people have tto read this and understawnd this side
    of your story. I can’t believe you are not more popular becausse
    you most certainly have the gift.

  13. September 5, 2014 at 8:54 am

    My programmer is tryong to persuade me too move to .net from PHP.
    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using Movable-type on several websites for about a year and am worried about swutching to another platform.
    I have heard good things about blogengine.net.
    Is here a way I can import all my wordpress content into it?
    Any kind of help would be greatly appreciated!

  14. September 5, 2014 at 4:05 pm

    Great blog! Is your thme custom made or did youu download it frolm somewhere?
    A theme likee yours with a few simple adjustements would really
    make my blog shine. Please let me know where yoou got your theme.
    Appreciate it

  15. September 7, 2014 at 4:07 am

    I just like the helpful info you provide for your articles.
    I will bookmark your weblog and test again here regularly.
    I’m moderately sure I’ll be told lots off new stuff right right here!
    Best of luck forr the following!

  16. September 8, 2014 at 6:40 am

    Hi, Neat post. There’s a problem along wigh your site in internet explorer, might check this?
    IEtill is tthe market chief and a big part of people wilkl leave ouut your fantastic writing
    because of this problem.

  17. September 21, 2014 at 9:32 pm

    Hey There. I found your blog using msn. This is an extremely well written article.
    I will make sure to bookmark it and coome back to read more off your
    useful information. Thanks for the post. I’ll definitely comeback.

  18. September 23, 2014 at 12:18 pm

    What a data of un-ambiguity and preserveness of valuable know-how
    regarding unpredicted emotions.

  19. September 23, 2014 at 12:30 pm

    This blog was… how do I say it? Relevant!!
    Finally I’ve found something that helped me. Cheers!

  20. September 23, 2014 at 1:29 pm

    Good post. I lesarn something new and challenging on sites I stumbleupon everyday.
    It will always be helpful tto read contnt from other writers and use a
    little something from other web sites.

  21. September 30, 2014 at 9:28 am

    each time i used to read smaller articles orr reviews that as well clear their
    motive, and that is also happening with this piece of
    writing which I am reading now.

  22. October 4, 2014 at 12:34 pm

    I was wondering if you evedr thought oof changing
    the page layout oof your site? Its very well written; I love what youve got to
    say. But maybe you could a little more in the way of content so people coyld
    connect with it better. Youve got an awful llot of text for only having one
    or 2 pictures. Maybe you could space it out better?

  1. No trackbacks yet.

Leave a reply to omega juicer 8006 Cancel reply