javaandroidonactivityresultregisterforactivityresult

Android use object in registerForActivityResult


In my AppCompatActivity, I declared an ActivityResultLauncher. I used registerForActivityResult() to create it and passed a LambdaExpression for the ActivityResultCallback.

However, I need a reference to an object in this ActivityResultCallback, which I have when calling launch().

Example code:

private final ActivityResultLauncher<Intent> launcher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
    object.doSomething();
});

method() {
    Object object = new Object();
    launcher.launch(new Intent(MainActivity.this, OtherActivity.class));
}

I could just save the object in a private field, but is this what Android intents us to do?

I understand that Android does not want you to share objects between different activities. But here, the reference should only be kept in my MainActivity.class.

Any help is appreciated!


Solution

  • I could just save the object in a private field, but is this what Android intents us to do?

    Yes, pretty much yes. Look at the fragment in the documentation:

    registerForActivityResult() is safe to call before your fragment or activity is created, allowing it to be used directly when declaring member variables for the returned ActivityResultLauncher instances.

    So it seems like the ActivityResultCallback is supposed to reference the declared instance variables, so You indeed

    could just save the object in a private field

    and it would be fine. The reference to that object would be private and it would, obviously, exist only in Your MainActivity.