-1

I am trying to get the image using picasso . Since startActivityForResult is depreciated I need to migrate to the new API . Code is as follows .

 private void openFileChooser() {
    Intent intent = new Intent();
    intent.setType("image/*");
    intent.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent, PICK_IMAGE_REQUEST);
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK
            && data != null && data.getData() != null) {
        mImageUri = data.getData();
        Picasso.get().load(mImageUri).into(productImage);
    }
}
Karunesh Palekar
  • 2,190
  • 1
  • 9
  • 18
Nusry KR
  • 105
  • 1
  • 3
  • 13
  • @snachmsm I checked that and tried but was unable to pick/select the image – Nusry KR Aug 30 '21 at 07:32
  • Results are changed by Android Devs. You can check this page. https://developer.android.com/training/basics/intents/result "While the underlying startActivityForResult() and onActivityResult() APIs are available on the Activity class on all API levels, it is strongly recommended to use the Activity Result APIs introduced in AndroidX Activity and Fragment." – Süleyman Bilgin Aug 30 '21 at 07:48

1 Answers1

1

Here is how you migrate to the new Api .

Step 1 : Declare a top variable in your class for getting image from the Gallery

ActivityResultLauncher<String> mGetContent = registerForActivityResult(new GetContent(),
    new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri uri) {
            //You are provided with uri of the image . Take this uri and assign it to Picasso
        }
});

Step 2 : Now in your OnCreate , set a onClickListener on your button via which you want the user to go to the Gallery and launch the contract in the following manner :


    selectButton.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            // Pass in the mime type you'd like to allow the user to select
            // as the input
            mGetContent.launch("image/*");
        }
    });

Comment below if you face any errors

Karunesh Palekar
  • 2,190
  • 1
  • 9
  • 18
  • Thanks, I tired initialized by `private Uri mImageUri` and take the Uri for assigning to Picasso `mImageUri = uri.normalizeScheme()` is this correct? – Nusry KR Aug 30 '21 at 09:50
  • You can do it directly using Picasso.get().load(uri).into(productImage) . This is also fine . If your method returns no error then that works as well . But no need to take those extra steps – Karunesh Palekar Aug 30 '21 at 09:56