Home > Mobile >  how to replace the startActivityForResult because its now deprecated this is the last piece i need t
how to replace the startActivityForResult because its now deprecated this is the last piece i need t

Time:08-03

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);

        }
    });

CodePudding user response:

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/*")

CodePudding user response:

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
            }
        });
  • Related