NOTE:

NOTE: Of late, I have been getting requests for very trivial problems that many of you are facing in your day-to-day work. This blog is not to solve your "project" problems - surely not a "Support" site.
I just love to share my knowledge in my spare time and would appreciate any questions or feedback on the articles and code I have shared. I also do appreciate thought-provoking questions that would lead me to write more articles and share.
But please do not put your day-to-day trivial problems here. Even if you do, you most probably would not get a response here.
Thanks

Search This Blog

Loading...
x

Monday, 31 August 2009

Fetching Result from a called activity - Android Tutorial for Beginners – (Part 5)


The next logical step in learning the Android development is to look at how can you call or invoke one activity from another and get back data from the called activity back to the calling activity. For simplicity sake, let us name the first calling activity as parent activity and the invoked activity as the child activity.


For simplicity sake, I use an explicit intent for invoking the child activity. For simple invocation without expecting any data back, we use the method startActivity(). However, when we want a result to be returned by the child activity, we need to call it by the method startActivityForResult(). When the child activity finishes with the job, it should set the data in an intent and call the method setResult(resultcode, intent) to return the data through the intent.


The parent activity should have overridden the method onActivityResult(…) in order to be able to get the data and act upon it.


NOTE: for successful execution of this sequence of events, the child activity should call finish() after setResult(..) in order to give back the handle to the parent activity.


In summary, here are the methods to implement in the parent activity:
  • 1.  startActivtyForResult(..)
  • 2.  onActivityResult(…)

The child Activity should complete the work as usual and finally call:
  • 1.  setResult(…)
  • 2.  finish()

Let us delve into the example downloadable here:


The calling Activity is providing 2 buttons to view books and pens. On selecting one of them, either BooksActivity or PensActivity is called, which displays a list (using ListView) of the selected type of objects. The user can select one and the selected object is returned to the parent for display. (Note: this could be extended into a shopping cart example. I have kept it simple for the tutorial’s sake)


Since we are expecting to get back the selected object, the calling Activity’s code is like this:
     Intent bookIntent = new Intent();                bookIntent.setClass(CallingActivity.this,BooksActivity.class);
      startActivityForResult(bookIntent,BOOK_SELECT);
where BOOK_SELECT is just a constant to help us identify from which child activity the is result obtained, when there is more than 1 child activity, as in this case.


At this point the control is handed over to the BooksActivity. This displays the list of books and the user can scroll through and select a book. When the user selects a book, the selected book needs to be passed back to the CallingActivity. This is how it is done:
      Object o = this.getListAdapter().getItem(position);
      String book = o.toString();
      Intent returnIntent = new Intent();
      returnIntent.putExtra("SelectedBook",book);
      setResult(RESULT_OK,returnIntent);       
      finish();


The first 2 lines show how to get the selected book from the ListView. Then, you create a new intent object, set the selected book as an extra and pass it back through the setResult(…) method call. The result code is set to RESULT_OK since the job has been successfully done.  After that the finish() method is called to give the control back to the parent activity.


In the parent, the method that gets the control is onActivityResult(…)
protected void onActivityResult(int requestCode, int resultCode, Intent data)
      {
      switch(requestCode) {
      case BOOK_SELECT:
            if (resultCode == RESULT_OK) {
                String name = data.getStringExtra("SelectedBook");
                Toast.makeText(this, "You have chosen the book: " + " " + name, Toast.LENGTH_LONG).show();
                break;
            }
      ……….
      }
      }  


Here you notice that the BOOK_SELECT constant is used to act upon the result. If the result code is RESULT_OK, we take the book selected from the “extra” of the intent that is returned from the child activity. data.getStringExtra("SelectedBook") is called to and the name returned is displayed through a Toast. 

58 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Wonderfull tutorial,learn a lot about android development.

    ReplyDelete
  3. No matter what I did, I never received FinishFromChild like I was expecting. I wonder if there is some reason activities with the show when locked or dismiss keyguard flags would not work with the result methods.

    ReplyDelete
  4. Thanx Sai Geetha...

    i was having a prob when it said u cant use void with onActivityResult.
    But now its all solved thanx to ur nice example :)

    ReplyDelete
  5. I didn't notice this at first, but the request code is passed in the first intent when startActivityForResult is called. That same request code comes back in the onActivityResult() method. Sweet Stuff - thanks for these tutorials!

    ReplyDelete
  6. thanks for your post ,they are simply great and easy to understand.I also suggest to post a tutorial on Handlers and Threads ,they are a bit difficult to understand by reading the documentation.I am saying this because your post comes handy when i could not understand by reading android documentation.

    ReplyDelete
  7. Hi Sai Geetha,

    Thanks for such a wonderful tutorial, it is helping me a lot as a beginner. I have a doubt in this exaample, why do you need the following code
    protected void start(Intent intent) {
    this.startActivityForResult(intent,BOOK_SELECT);
    }
    I removed this part, example is still working fine.

    ReplyDelete
  8. Hi rahul,

    You are right. There is no use for the piece of code you mentioned. I had written that first and then changed the implementation. Forgot to remove this redundant piece of code.
    Thanks for pointing it out.

    ReplyDelete
  9. Thanks so much! This helped me a lot!

    ReplyDelete
  10. Perfect. This is what I was looking for. Thanks

    ReplyDelete
  11. geetha garu ,Im ettin errors ike nullpointerexception from child activity when it is about to finish??!! this is my code

    Intent i = new Intent();
    Bundle b = new Bundle();
    b.putString("name",name);
    b.putString("dep", dep);
    i.putExtras(b);
    setResult(Activity.RESULT_OK);
    finish();

    and used onActivityResult() in parent activity but still its hell!!?? whaat to do?? i want to return those 2 strings to parent activity!!

    ReplyDelete
  12. geetha garu ,Im ettin errors ike nullpointerexception from child activity when it is about to finish??!! this is my code

    Intent i = new Intent();
    Bundle b = new Bundle();
    b.putString("name",name);
    b.putString("dep", dep);
    i.putExtras(b);
    setResult(Activity.RESULT_OK);
    finish();

    and used onActivityResult() in parent activity but still its hell!!?? whaat to do?? i want to return those 2 strings to parent activity!!

    ReplyDelete
  13. Hi Ash,

    What your doing is obviously not correct. You are setting the strings into the intent but you are not passing it back to the activity through your setResult(..) method.

    Apart from just saying Activity.RESULT_OK, you should also pass the intent i back it should be
    setResult(Activity.RESULT_OK, i);
    finish();

    Only then it gets passed back. Otherwise no magical way of passing it back.

    ReplyDelete
  14. Your tutorials teach android basics in a simple down to earth examples. Thank you very much.

    ReplyDelete
  15. Really very usefull tutorial. Thanks for such short and sweet example

    ReplyDelete
  16. wonderful tutorial .......it helps a lot...will u plz help me in remote method access in android.....(method is in wsdl format )how can i run this in android...

    ReplyDelete
  17. Tremendous post, excellent explanation. You are clearly a great teacher.

    ReplyDelete
  18. Thanks for the tutorial. I'keep getting "duplicate method onClick(View)in type new View.OnClickListener". I tried changing onClick(View) to onClick1(View), 2,etc, per Eclipse suggestion. It seemed to get rid of the errors, but I'm sure it caused more harm than good.

    I am new to Android and I come across this problem a lot. I would rather learn the proper method than develop bad habits and dirty code.

    ReplyDelete
  19. Hi Sai

    if we force fully get back from child activity then what is resultcode come?

    gives an error null pointer exception

    what does?

    ReplyDelete
  20. Thanks a lot, it was very useful your explanation

    ReplyDelete
  21. hi geeta.. i have a doubt..
    please help me

    i need to develop an application which searches android market for specific app and displays .. i need app name to be filled in my text box.. how to do that ?

    code goes like this :
    intent.setData(Uri.parse("market://search?q=pname:some package name"));
    startActivity(intent);


    this will display result..but i need it on textbox .. please help me

    ReplyDelete
    Replies
    1. you need to use Web services I think.

      Delete
  22. Hi Sai,
    The article is very very nice.....Could you please explain how to transfer/share the data from one application to another application using Intents.

    IS there any way to do this?

    ReplyDelete
  23. Hi Pravin Pawar,

    if we force fully get back from child activity it goes to onFinish()/onDestroy() override methods. So,there you can specify the resultcode.So,we handle the eror null pointer exception.

    ReplyDelete
  24. iam doing a game...whenever i get a call or mesg and come out of the application.again if we enter it gives force close error..can u plzz help me wht shd be done...i think thr is an error in the thread..iam using all the thread release code in destroy,pause......plzz help

    ReplyDelete
  25. Madam you have given the sample code....
    protected void onActivityResult(int requestCode, int resultCode, Intent data)

    {

    switch(requestCode) {

    case BOOK_SELECT:

    if (resultCode == RESULT_OK) {

    String name = data.getStringExtra("SelectedBook");

    Toast.makeText(this, "You have chosen the book: " + " " + name, Toast.LENGTH_LONG).show();

    break;

    }

    ……….

    }

    }

    but i think we have to send the data to super class....so there will be a line like..
    super.onActivityResult(requestCode,resultCode,data);

    am i right madam?

    ReplyDelete
  26. Thanks a lot for all this tutorials. They are really helpful!

    Cheers,

    Marcos

    ReplyDelete
  27. This is good tutorial but i like following links because it explain how to store as well as read values that we pass while we use startActivityForResult()

    http://micropilot.tistory.com/category/Android/startActivityForResult

    ReplyDelete
  28. I LOVE YOU !!
    <3 <3 <3

    ReplyDelete
  29. i have one custom list view and having 8 items in it.
    i have same data for each item just having little bit changes. so i want to load data from DB to one activity. but i want to load data of each item in only single activity. is it possible or should i go for activity for each item.

    ReplyDelete
  30. if u have sample code for this or link mail me at
    sachinsandbhor@hotmail.com

    ReplyDelete
  31. Hi! thanks for the wonderful tutorial. I was wondering how do i handle the scenario when there are multiple startOnActivityForResults??
    Thanks

    ReplyDelete
  32. HI Geetha;

    Parent Activity I am calling like this :

    Intent showContent = new Intent(v.getContext(),SalesRouteDevitionActivity.class);
    Bundle bundle = new Bundle();
    bundle.putString("RouteName", keyword);
    showContent.putExtras(bundle);
    startActivityForResult(showContent, 5);

    And

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // super.onActivityResult(requestCode, resultCode, data);
    Log.i("****" , "requestCode" + requestCode);
    Intent intent = new Intent(SalesRouteActivity.this,ListRetailerActivity.class);
    Bundle bundle = new Bundle();
    bundle.putString("RouteName", keyword);
    intent.putExtras(bundle);
    View view = SalesActivityGroup.group.getLocalActivityManager()
    .startActivity("",intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)).getDecorView();
    SalesActivityGroup.group.replaceView(view);
    }


    Child Activity Like this

    Intent returnIntent = new Intent();
    setResult(Activity.RESULT_OK, getIntent());
    finish();


    I am using this in tab ActivityGroup.My problem is once finish child activity, it didn't go to onActivityResult...

    Please help me

    ReplyDelete
  33. Hii geeta.. can u explain me by example what is context,getapplicationcontext,getbasecontext?

    ReplyDelete
  34. ,klasldfjl
    sdf sdf s sdf

    ReplyDelete
  35. Hi geeta,

    I have two textview and on click on that i am calling nextActivity(i.e RetrieveActivity.java) here i am getting the value from getIntent.getStringExtra. now how can i check the condition whether it is addition or Subtraction? i am not able to check the condition using if...else in retrieveActivity.java



    private OnClickListener addViewListener = new OnClickListener() {

    @Override
    public void onClick(View v) {

    Log.d("Inside the addViewlistener again" , " ");
    Bundle bundle = new Bundle();
    bundle.putString("Addition",addviewGettext);
    Intent intent = new Intent(Math4KidsActivity.this, RetrieveActivity.class);
    intent.putExtras(bundle);
    //intent.putExtra("Addition",addviewGettext);
    startActivityForResult(intent, 1);

    }
    };

    private OnClickListener subViewListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
    Bundle bundle = new Bundle();
    bundle.putString("Subtraction",subviewGettext);
    Intent intent1 = new Intent(Math4KidsActivity.this,RetrieveActivity.class);
    //intent1.putExtra("Addition",addviewGettext);
    intent1.putExtras(bundle);

    startActivityForResult(intent1, 2);
    }
    };

    ReplyDelete
  36. THANKS A LOT !! PERFECT ..

    ReplyDelete
  37. Great tutorial!!!

    ReplyDelete
  38. Well done... and happy new year

    ReplyDelete
  39. Android is a growing market. And thanks for all the information and tips and coding for Android development.

    ReplyDelete
  40. hi sai,
    Can u explain why we have used a protected void start(Intent intent) ..function in the above program

    ReplyDelete
  41. hi sai,
    Thank u for giving me such a valuable tutorial.

    ReplyDelete
  42. Hi Sai,

    Great tutorial - and really well explained on the requestCode/BOOK_SELECT in the code.

    Ta very much

    ReplyDelete
  43. Hi Geetha,

    Can you tell me diff between simple_list_item_1 and simple_list_item_2
    Thanks in advance

    ReplyDelete
  44. thank you, helped a lot!

    ReplyDelete
  45. Sai Geetha, you've helped me out several times with seemingly simple stuff, but no one else can explain it as clearly as you can. Thanks.

    ReplyDelete
  46. Each time I read your article it really helps me a lot.. Thank u very much and keep doing good work that will be understandable by all and simple.

    ReplyDelete
  47. thanks......for this post...
    keep it updating with new blog
    i like ur all blog.
    and it should helpful for me..

    ReplyDelete
  48. you are great help thank u very much i had problem finding this..... <3

    ReplyDelete
  49. Sai , Intent and result fetch tutorial is awesome. since i am database developer and new to android development and it is difficult for me to read the android documentation and work.With my basic java knowledge i am able to grab the concepts easily from your explanation and wont even forget at any point if someone ask me. One of the finest blog to understand android concepts in simple and effective way

    Many thanks for your contribution and knowledge sharing

    Kannan K

    ReplyDelete
  50. Thank you detailed explanation helps in understanding the concept

    ReplyDelete
  51. Thank you for your kind information...

    ReplyDelete
  52. i wanaa know about the method onActivityResult is it a default method or the user method, when ever i change the name of this method it doesnt toast the result, any body plz explain me....

    ReplyDelete
  53. thanks a million,its really help me to solve this problem,

    ReplyDelete