Home > Blockchain >  Button that sets imageView from the gallery, within fragment
Button that sets imageView from the gallery, within fragment

Time:07-24

I have tried many different solutions that I have found, this seems to be the closest i've been to getting this section to work. When debugging the bundle is shows as null.

onActivityResult Launcher

    activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), new ActivityResultCallback <ActivityResult>() {
        @Override
        public void onActivityResult(ActivityResult result) {
            if (result.getResultCode() == RESULT_OK && result.getData() != null) {
                Bundle bundle = result.getData().getExtras();
                Bitmap bitmap = (Bitmap) bundle.get("data");


                imagePP.setImageBitmap(bitmap);
            }
        }
    });

onClickListener

    add1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            Intent intent = new Intent(Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

                activityResultLauncher.launch(intent);
        }

    });

CodePudding user response:

The Activity Result guide uses selecting an image as its example, which uses the GetContent contract, which allows users to select images from any source (e.g., Google Photos, Google Drive, etc.) in addition to locally available images.

Importantly, you should always be using the returned Uri and not relying on a thumbnail Bitmap:

ActivityResultLauncher<String> activityResultLauncher = registerForActivityResult(new GetContent(),
    new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(@Nullable Uri uri) {
            if (uri != null) {
                imagePP.setImageURI(uri);
            }
        }
});
add1.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        activityResultLauncher.launch("image/*");
    }

});
  • Related