简体   繁体   中英

Android pick an image from gallery

In fragment I am calling gallery intent like this:

         // Create the Intent for Image Gallery.
        Intent i = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(i, MainActivity.LOAD_IMAGE_RESULTS);

And in main activity I am handling result with following code:

public static int LOAD_IMAGE_RESULTS = 1;
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    Log.w("reqestCode:",""+requestCode);
    if(requestCode == LOAD_IMAGE_RESULTS && data != null && data.getData() != null) {
        Uri _uri = data.getData();

        //User had pick an image.
        Cursor cursor = getContentResolver().query(_uri, new String[] { android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
        cursor.moveToFirst();

        //Link to the image
        final String imageFilePath = cursor.getString(0);
        Log.w("ImageFile",imageFilePath);
        cursor.close();
    }
}

But in onActivityResult requestCode is returning 196609 value.So my code is not working.How can I resolve it ?

Looks issue is with your Intent that you created. Try something like this:

                pictureActionIntent = new Intent(
                        Intent.ACTION_GET_CONTENT, null);
                pictureActionIntent.setType("image/*");
                pictureActionIntent.putExtra("return-data", true);
                startActivityForResult(pictureActionIntent,
                        GALLERY_PICTURE);

For more information check this answer.

You said you're calling this from the Fragment . Have you tried listening to the onActivityResult in both places? The Activity as well as the Fragment ? It's worth a shot. :)

try this code it will works // start the activity

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

//in onactivity result get the bitmap

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {
        if (requestCode == GALLERY_INTENT_CALLED) {
            if (null == data)
                return;
            String selectedImagePath;
            Uri selectedImageUri = data.getData();
            // MEDIA GALLERY
             Bitmap bitmap = BitmapFactory.decodeFile(ImageFilePath.getPath(
                    getApplicationContext(), selectedImageUri));
            ivProfileImage.setImageBitmap(bitmap);

        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM