In my android app, I have a main activity which creates two other sub activites through intent. Now, both the sub activity return result to the main activity. In my main act
It's possible to return any kind of data from a subactivity in the result intent parameter:
Sub-activity:
Intent intent = new Intent ();
intent.putExtra ("string_1", "hello");
intent.putExtra ("string_2", "world");
intent.putExtra ("int_1", 1000);
intent.putExtra ("long_1", 2000l);
activity.setResult (Activity.RESULT_OK, intent);
_
Parent activity:
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent intent)
{
if (resultCode == Activity.RESULT_OK)
{
String string_1 = intent.getStringExtra ("string_1", "");
String string_2 = intent.getStringExtra ("string_2", "");
int int_1 = intent.getIntExtra ("int_1", 0);
long long_1 = intent.getLongExtra ("long_1", 0);
}
}
You change the requestCode
that you use when you call startActivityForResult
.
EDIT: for example, I use this:
startActivityForResult(i, App.REQUEST_ENABLE_BT);
and this:
startActivityForResult(i, App.MANUAL_INPUT);
and then you filter the results like this:
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
switch(requestCode){
case App.REQUEST_ENABLE_BT:
if(resultCode != RESULT_OK){
Toast.makeText(this, getString(R.string.label_bluetooth_disabled), Toast.LENGTH_LONG).show();
}
break;
case App.MANUAL_INPUT:
break;
}
}
That's what the requestCode
is for. So you'd have a setup like this
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode)
case ACTIVITY1:
if(resultCode == RESULT_OK)
Toast.makeText(getApplicationContext(), "Activity 1 returned OK", Toast.LENGTH_LONG).show();
break;
case ACTIVITY2:
if(resultCode == RESULT_OK)
Toast.makeText(getApplicationContext(), "Activity 2 returned OK", Toast.LENGTH_LONG).show();
break;
}
Where ACTIVITY1 and ACTIVITY2 are constants in your Activity
. You'd call them like so:
startActivityForResult(activity1Intent, ACTIVITY1);
and
startActivityForResult(activity2Intent, ACTIVITY2);
You can use swicth the requestcode for different result
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case (1):
{
// do this if request code is 1.
}
break;
case (2):
{
// do this if request code is 2.
}
break;
}