Because startActivityForResult is deprecated.
So I replace startActivityForResult to registerForActivityResult
This is my code:
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();
}
}
});
Because i call to multi Activity:
Old Version:
Intent myinten = new Intent(MainActivity.this, MainActivity2.class);
startActivityForResult(myinten, 111);
Intent myinten = new Intent(MainActivity.this, MainActivity3.class);
startActivityForResult(myinten, 222);
New Version:
Intent myinten = new Intent(MainActivity.this, MainActivity2.class);
someActivityResultLauncher.launch(myinten);
Intent myinten = new Intent(MainActivity.this, MainActivity3.class);
someActivityResultLauncher.launch(myinten);
Can we to send & get "requestCode" with "registerForActivityResult"?
Either create a new ActivityResultLauncher for each launch or pass your own identifier in a bundle when launching the activity.
ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
new ActivityResultCallback<ActivityResult>() {
@Override
public void onActivityResult(ActivityResult result) {
if (result.getResultCode() == Activity.RESULT_OK) {
Intent intent = result.getData();
//get your "requestCode" here with switch for "SomeUniqueID"
}
}
});
Launch Activity
Intent myinten = new Intent(MainActivity.this, MainActivity2.class);
myinten.putExtra("requestCode", "SomeUniqueID");
someActivityResultLauncher.launch(myinten);
Activity which returns
Intent intent = new Intent();
//these should not be hard coded, but retrieved from the intent which created this activity
intent.putExtra("requestCode", "SomeUniqueID");
activity.setResult(Activity.RESULT_OK, intent);
activity.finish();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With