skip to Main Content

how to replace it with ActivityResultLauncher.
sorry guys i am just new to coding and programming.

SelectImageGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            Intent intent = new Intent();

            intent.setType("image/*");

            intent.setAction(Intent.ACTION_GET_CONTENT);

            startActivityForResult(Intent.createChooser(intent, "Select Image From Gallery"), 1);

        }
    });

2

Answers


  1. You need to register for activity result outside of onCreate using below Kotlin code

       val getContent = registerForActivityResult(ActivityResultContracts.GetContent()) { uri: Uri? ->
    
                    // Callback after selecting image
                    // Do whatever you want to do with uri
    
                }
            }
        }
    

    Now instead of startActivityForResult(..) call below method when you want to open gallery to pick image

     getContent.launch("image/*")
    
    Login or Signup to reply.
  2. SelectImageGallery.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
    
            Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
            intent.addCategory(Intent.CATEGORY_OPENABLE)
            intent.setType("image/*");
    
            intent.setAction(Intent.ACTION_GET_CONTENT);
    
            result.launch(Intent.createChooser(intent, "Select Image From Gallery"));
    
        }
    });
    

    INSIDE SAME METHOD AS LISTENER:

        ActivityResultLauncher<String> result = registerForActivityResult(
            new ActivityResultContracts.GetContent(),
            new ActivityResultCallback<Uri>() {
                @Override
                public void onActivityResult(Uri result) {
                    //DO whatever with received image content scheme Uri
                }
            });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search