Search code examples
androidandroid-studioandroid-activity

ActivityResultContract opens gallery twice


I'm currently switching the ActivityResults on an Android app (java) with ActivityResultContract (because of deprecation) as suggested by Google https://developer.android.com/training/basics/intents/result. Example code

When I implement the same example code to get an image from gallery, shown in the link above, the activityResult opens not only the default image chooser, but also asks me to choose an app to select the image: App opening image chooser and asking to choose an app

Is there a way to avoid asking for an app to choose an image?


Solution

  • You can use ActivityResultLauncher instead. It will open the system gallery to pick an image from it.

    Just follow these steps :-

    1. First create the ActivityResultLauncher like this :

      ActivityResultLauncher<String> mGetContent = 
               registerForActivityResult(new GetContent(), new ActivityResultCallback<Uri>() {
       @Override
       public void onActivityResult(Uri uri) {
         // Handle the returned Uri
       }
      });
      
    2. Then, launch system image picker on button click or whenever you want.

      mGetContent.launch("image/*");