Handling onActivityResult in an Android app with multiple actions

In my Android app, I have a main action that creates two other sub-activities through intent. Now both results return to the main action. In my main activity, how to handle two "onActivityResult (int requestCode, int resultCode, Intent data)" since it cannot have two methods with the same name in this class. Hope my question is clear.

thanks

+6
source share
4 answers

You change the requestCode that you use when calling 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 as follows:

 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; } } 
+10
source

What is requestCode ? So you will have this setup

 @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; } 

If ACTIVITY1 and ACTIVITY2 are constants in your Activity . You would call them that:

startActivityForResult(activity1Intent, ACTIVITY1);

and

startActivityForResult(activity2Intent, ACTIVITY2);

+9
source

You can return any data from subactivity to 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); } } 
+3
source

You can use swicth request code for another 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; } 
+1
source

Source: https://habr.com/ru/post/896348/


All Articles