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.
This comment has been removed by the author.
ReplyDeleteWonderfull tutorial,learn a lot about android development.
ReplyDeleteNo 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.
ReplyDeleteThanx Sai Geetha...
ReplyDeletei was having a prob when it said u cant use void with onActivityResult.
But now its all solved thanx to ur nice example :)
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!
ReplyDeletethanks 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.
ReplyDeleteHi Sai Geetha,
ReplyDeleteThanks 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.
Hi rahul,
ReplyDeleteYou 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.
Thanks so much! This helped me a lot!
ReplyDeletePerfect. This is what I was looking for. Thanks
ReplyDeletegeetha garu ,Im ettin errors ike nullpointerexception from child activity when it is about to finish??!! this is my code
ReplyDeleteIntent 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!!
geetha garu ,Im ettin errors ike nullpointerexception from child activity when it is about to finish??!! this is my code
ReplyDeleteIntent 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!!
Hi Ash,
ReplyDeleteWhat 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.
Your tutorials teach android basics in a simple down to earth examples. Thank you very much.
ReplyDeleteReally very usefull tutorial. Thanks for such short and sweet example
ReplyDeletewonderful 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...
ReplyDeleteTremendous post, excellent explanation. You are clearly a great teacher.
ReplyDeleteThanks 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.
ReplyDeleteI 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.
Hi Sai
ReplyDeleteif we force fully get back from child activity then what is resultcode come?
gives an error null pointer exception
what does?
Thanks a lot, it was very useful your explanation
ReplyDeletehi geeta.. i have a doubt..
ReplyDeleteplease 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
you need to use Web services I think.
DeleteVery Nice Tutorial...
ReplyDeleteHi Sai,
ReplyDeleteThe 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?
Hi Pravin Pawar,
ReplyDeleteif 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.
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
ReplyDeleteMadam you have given the sample code....
ReplyDeleteprotected 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?
Thanks a lot for all this tutorials. They are really helpful!
ReplyDeleteCheers,
Marcos
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()
ReplyDeletehttp://micropilot.tistory.com/category/Android/startActivityForResult
I LOVE YOU !!
ReplyDelete<3 <3 <3
i have one custom list view and having 8 items in it.
ReplyDeletei 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.
if u have sample code for this or link mail me at
ReplyDeletesachinsandbhor@hotmail.com
Hi! thanks for the wonderful tutorial. I was wondering how do i handle the scenario when there are multiple startOnActivityForResults??
ReplyDeleteThanks
HI Geetha;
ReplyDeleteParent 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
Hii geeta.. can u explain me by example what is context,getapplicationcontext,getbasecontext?
ReplyDelete,klasldfjl
ReplyDeletesdf sdf s sdf
Hi geeta,
ReplyDeleteI 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);
}
};
THANKS A LOT !! PERFECT ..
ReplyDeleteGreat tutorial!!!
ReplyDeleteWell done... and happy new year
ReplyDeleteAndroid is a growing market. And thanks for all the information and tips and coding for Android development.
ReplyDeletehi sai,
ReplyDeleteCan u explain why we have used a protected void start(Intent intent) ..function in the above program
hi sai,
ReplyDeleteThank u for giving me such a valuable tutorial.
Hi Sai,
ReplyDeleteGreat tutorial - and really well explained on the requestCode/BOOK_SELECT in the code.
Ta very much
Hi Geetha,
ReplyDeleteCan you tell me diff between simple_list_item_1 and simple_list_item_2
Thanks in advance
thank you, helped a lot!
ReplyDeletethank you.............
ReplyDeleteSai 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.
ReplyDeleteEach 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.
ReplyDeletethanks......for this post...
ReplyDeletekeep it updating with new blog
i like ur all blog.
and it should helpful for me..
thank you.............
ReplyDeleteyou are great help thank u very much i had problem finding this..... <3
ReplyDeleteSai , 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
ReplyDeleteMany thanks for your contribution and knowledge sharing
Kannan K
Thank you detailed explanation helps in understanding the concept
ReplyDeleteThank you for your kind information...
ReplyDeletei 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....
ReplyDeletethanks a million,its really help me to solve this problem,
ReplyDeleteThanks a lot for this blog!!!
ReplyDeleteEasiest explanation i ve ever found! Clear and to the point! Thank you so much for this! bless you!
ReplyDeleteYou've selected only one value and send to the parent that is very easy, but what if I want to add multiple values and send to the parent activity. How to get multiple values in parent activity? Plz help me out this
ReplyDeleteThanks in advance
Thnks many many thanks....... your example is so simple and so easy to learn
ReplyDelete