Adding Intent setAction to the new Activity Result API ActivityResultLauncher when selecting Image from Gallery

1.1k Views Asked by At

I am using the new Activity Result API for launching and picking an image from Gallery the problem am having is how can i modify an Intent in the new Activity Result API to work like the old startActivityForResult

Below is my old way of selecting something from Gallery


        Intent pickImageIntent = new Intent();
        pickImageIntent.setType("image/*");
        pickImageIntent.setAction(Intent.ACTION_PICK);
        startActivityForResult(pickImageIntent, PICK_IMAGE_FROM_GALLERY_REQUEST_CODE);

Then below is my old way of getting result using onActivityResult


@Override
    public void onActivityResult(int requestCode, int resultCode,
                                 @Nullable @org.jetbrains.annotations.Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == PICK_IMAGE_FROM_GALLERY_REQUEST_CODE) {
            if (resultCode == RESULT_OK && data != null) {

                Uri selectedImageUri = data.getData();

                imvImage.setImageURI(selectedImageUri);

            } else {
                // Show Error Exception Dialog
                // We encountered an error while picking your image from gallery
                // Try Again, Cancel
            }
        }
}

Below is my new way of launching the camera using the new Activity Result API


getImageFromGallery.launch("image/*");

And getting results below using ActivityResultLauncher


ActivityResultLauncher<String> getImageFromGallery = registerForActivityResult(new ActivityResultContracts.GetContent(),
            new ActivityResultCallback<Uri>() {
                @Override
                public void onActivityResult(Uri uri) {

                    imvImage.setImageURI(uri);
                }
            });

My question is how can i parse something something to the launch method or set action to intent example

pickImageIntent.setAction(Intent.ACTION_PICK);

to this

 getImageFromGallery.launch("image/*");

0

There are 0 best solutions below