Its a common operation in Android application to launch new activity all the time. There are times when you want to receive the result from new activity started. For example in one of my recent projects I have to launch settings activity (SettingsActivity) to set the mode of application and when this activity is closed it should return the selected mode to the caller activity (MainActivity).
How child Activity returns result
Activity class has a method setResult which sets the result code to be returned to parent activity. Another overload of setResult allows you to pass Intent also for any extra data to be sent.
In my SettingsActivity I have code like this
Activity class has method onActivityResult which we can override to receive the result from any child Activity started. Here is how I use onActivityResult in MainActivity to receive results from SettingsActivity
Starting child activity to receive result
To start Activity when you want to receive result from that Activity in onActivityResult you use method startActivityForResult. Here is how I start SettingsActivity from my MainActivity
How child Activity returns result
Activity class has a method setResult which sets the result code to be returned to parent activity. Another overload of setResult allows you to pass Intent also for any extra data to be sent.
In my SettingsActivity I have code like this
if (settingsSavedByUser()){How parent Activity receive result
Intent i=new Intent();
i.putExtra("mode","selectedApplicationMode");
setResult(RESULT_OK,i); //RESULT_OK and Intent(i) will be returned to parent
}else{
setResult(RESULT_CANCELLED); //RESULT_CANCELLED will be returned to parent
}
Activity class has method onActivityResult which we can override to receive the result from any child Activity started. Here is how I use onActivityResult in MainActivity to receive results from SettingsActivity
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data){
//SETTINGS_REQUEST_CODE is defined in my app as an integer (98621)
if (requestCode==SETTINGS_REQUEST_CODE){
if (resultCode==RESULT_OK){
//it means settings were save so we can get selected application
//mode from Intent(data)
String selectedMode=data.getExtras().getString("mode","");
Toast toast = Toast.makeText(this,"Selected mode: "+selectedMode,Toast.LENGTH_SHORT);
toast.show();
}else{
Toast toast = Toast.makeText(this,"Cancelled",Toast.LENGTH_SHORT);
toast.show();
}
}
super.onActivityResult(requestCode,resultCode,data);
}
Starting child activity to receive result
To start Activity when you want to receive result from that Activity in onActivityResult you use method startActivityForResult. Here is how I start SettingsActivity from my MainActivity
Intent i=new Intent(this,SettingsActivity.class);
startActivityForResult(i,SETTINGS_REQUEST_CODE);
Comments
Post a Comment
Share your wisdom