android pick images from gallery (now startActivityForResult is depreciated)

Viewed 1550

I believe many people have asked this question long time ago. Now, startActivityForResult is depreciated and I am looking for its replacement.

Previous code would be

        public void onClick(View v) {
        Intent intent = new Intent();
        intent.setType("image/*");
        intent.setAction(Intent.ACTION_GET_CONTENT);
        startActivityForResult(
                Intent.createChooser(
                        intent,
                        "Select Image from here..."),
                PICK_CODE);
2 Answers

Use this,

ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    image = (ImageView) findViewById(R.id.display_image);
}

public void pickAImage(View view) 
{
 Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
 photoPickerIntent.setType("image/*");
 someActivityResultLauncher.launch(photoPickerIntent);
}

Then do the operation,

ActivityResultLauncher<Intent> someActivityResultLauncher = registerForActivityResult(
        new ActivityResultContracts.StartActivityForResult(),
        result -> {
            if (result.getResultCode() == Activity.RESULT_OK) {
                // There are no request codes
                // doSomeOperations();
                Intent data = result.getData();
                Uri selectedImage = Objects.requireNonNull(data).getData();
                InputStream imageStream = null;
                try {
                    imageStream = getContentResolver().openInputStream(selectedImage);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
                BitmapFactory.decodeStream(imageStream);
                image.setImageURI(selectedImage);// To display selected image in image view
            }
        });

While startActivityForResult is still working, it has been marked as "depreciated" in my android studio. Documents provided by CommonsWare and ianhanniballake are helpful. I also found that someone has asked this question before and there is an answer for it.

OnActivityResult method is deprecated, what is the alternative?.

Related