Uri returned after ACTION_GET_CONTENT from gallery

2019-03-18 19:59发布

问题:

I am fetching Uri of a image from gallery using

Intent intent = new Intent();  
intent.setType("image/*");  
intent.setAction(Intent.ACTION_GET_CONTENT);  
startActivityForResult(Intent.createChooser(intent, "Choose Picture"), requestCode);

and trying to display the image by

imageView.setImageURI(uri);

here, uri is Uri of the image received in onActivityResult by intent.getData().

but no image is being displayed. Also, for

File file=new File( uri.getPath() );

file.exists() is returning false.

回答1:

The problem is that you getting the Uri but from that uri you have to create Bitmap to show in your Imageview. There are various mechanism to do the same one among them is this code.

Intent intent = new Intent();  
intent.setType("image/*");  
intent.setAction(Intent.ACTION_GET_CONTENT);  
startActivityForResult(Intent.createChooser(intent, "Choose Picture"), 1);

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) 
{
    if(resultCode==RESULT_CANCELED)
    {
        // action cancelled
    }
    if(resultCode==RESULT_OK)
    {
        Uri selectedimg = data.getData();
        imageView.setImageBitmap(MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedimg));
    }
}


回答2:

You need to get path from returned uri cursor. See the solution here: How to convert Android Uri to Java URI



回答3:

Launch the Gallery Image Chooser

Intent intent = new Intent();
// Show only images, no videos or anything else
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
// Always show the chooser (if there are multiple options available)
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);

PICK_IMAGE_REQUEST is the request code defined as an instance variable.

private int PICK_IMAGE_REQUEST = 1;

Show Up the Selected Image in the Activity/Fragment

@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) {

        Uri uri = data.getData();

        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
            // Log.d(TAG, String.valueOf(bitmap));

            ImageView imageView = (ImageView) findViewById(R.id.imageView);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Your layout will need to have an ImageView like this:

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/imageView" />