'How to handle request code in Android ActivityResultLauncher api
After updating my app to AndroidX I noticed startActivityForResult() is depreciated. I looked through the documentation and found some good explanations, but I'm still confused as to how to handle request codes. I've tried adding the request code param to onActivityResult, but obviously that does not work. This is my old onActivityResult.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_1) {
fetchTags();
} else if (requestCode == REQUEST_CODE_2) {
if (resultCode == RESULT_CANCELED) {
finish();
}
}
}
Do I need to create separate ActivityResultLaunchers for both request codes?
Solution 1:[1]
There is no need of Request Codes in the new API. You launch individual intents and you get results under their own scopes.
Old Way
public void openSomeActivityForResult() {
Intent intent = new Intent(this, SomeActivity.class);
startActivityForResult(intent, 123);
}
@Override
protected void onActivityResult (int requestCode, int resultCode, Intent data) {
if (resultCode == Activity.RESULT_OK && requestCode == 123) {
doSomeOperations();
}
}
New Way
// You can do the assignment inside onAttach or onCreate, i.e, before the activity is displayed
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
// There are no request codes
Intent data = result.getData();
doSomeOperations();
}
}
});
public void openSomeActivityForResult() {
Intent intent = new Intent(this, SomeActivity.class);
someActivityResultLauncher.launch(intent);
}
You can find more info in the documentation https://developer.android.com/training/basics/intents/result
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | che10 |