How to use registerForActivityResult with androidx.fragment.app.Fragment?

Viewed 13267
 ActivityResultLauncher<Intent> launcherImportFileSelection = requireActivity().registerForActivityResult(...

If the above code is placed in onCreate(Bundle savedInstanceState), the following exception is thrown:

Exception: LifecycleOwner MyActivity@868498a is attempting to register while current state is RESUMED. LifecycleOwners must call register before they are STARTED.

If it is placed in the constructor or as a declaration, requireActivity() throws the following exception:

java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Constructor.newInstance0(Native Method)
        at java.lang.reflect.Constructor.newInstance(Constructor.java:343)
2021-04-17 15:15:41.948 27930-27930/net.biyee.onvifer E/AndroidRuntime:     at androidx.fragment.app.Fragment.instantiate(Fragment.java:613)
            ... 42 more
     Caused by: java.lang.IllegalStateException: Fragment MyFragment{fba6d22} (e0d1f006-996d-4051-9839-4575a92e33dd) not attached to an activity.
        at androidx.fragment.app.Fragment.requireActivity(Fragment.java:928)

I have the following in build.gradle:

implementation 'androidx.fragment:fragment:1.3.2'

Could anyone offer a tip on this?

Update:

The problem has been solved. Please see my exchange with @CommmonsWare.

1 Answers

You need to set a register call outside the onCreate() method and in addition you need to put the registerForActivityResult() variable as a property of the fragment class. (Works only for Activity instead of Fragment!)

Register call example for KOTLIN:

val getContent = registerForActivityResult(GetContent()) { uri: Uri? ->
// Handle the returned Uri

}

Register call example for JAVA:

// GetContent creates an ActivityResultLauncher<String> to allow you to pass
// in the mime type you'd like to allow the user to select
ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
    new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {
            // Handle the returned Uri
        }
});

This documentation will help you to understand and practice. Cheers :)

Related