Home > database >  ACTION_GET_CONTENT to get image returns null URI
ACTION_GET_CONTENT to get image returns null URI

Time:11-30

I have an published app that uses an ACTION_GET_CONTENT intent to let the user select one of his/her pictures. Here's the code that launches the intent:

Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, false);
intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
intent.putExtra(Intent.CATEGORY_OPENABLE, true);
startActivityForResult(Intent.createChooser(intent, getString(R.string.select_pic)), SELECT_IMAGE);

And here's the onActivityResult:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data)
{
    if(resultCode == RESULT_OK) {
        if (requestCode == SELECT_IMAGE) {
            if (data != null) {
                Uri uri = data.getData();
                ...
                }
            }
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}

The problem here is that, on some devices, uri is null even though the user has selected an image. Mostly Samsung devices and also some Motorola phones. I also tried with ACTION_PICK instead of ACTION_CONTENT, but it happenned too in some other devices. So I would like to know if there's a way to let the user pick a picture that is universal.

Some phones that suffer this issue are:

  • Samsung galaxy A21S - Android 11 (SDK 30)
  • Samsung galaxy A3 (2016) - Android 7.0 (SDK 24)
  • Motorola moto e6 play - Android 9 (SDK 28)

Some of the users of these affected devices are notifying that it happens only sometimes.

CodePudding user response:

OnActivityResult deprecated

Try the new way

ActivityResultLauncher<String> launcher;

.....

Button pick = findViewById(R.id.pick);
pick.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                launcher.launch("image/*");
            }
        });

launcher = registerForActivityResult(new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
        @Override
        public void onActivityResult(Uri result) {
            
        }
    });

}

CodePudding user response:

Try this solution

val getImage = registerForActivityResult(ActivityResultContracts.GetContent()) {
        if (it != null) {
            binding.image.setImageURI(it)
        }
    }
    binding.image.setOnClickListener {
        getImage.launch("image/*")
    }
  • Related