简体   繁体   中英

How to get Real path from URI android Lollipop

I've tried this but with no luck.

 @Override
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();

        nameView.setText(selectedImage.toString());
        realPath = getRealPathFromURI(this, selectedImage);
        Toast.makeText(MainActivity.this, realPath, Toast.LENGTH_LONG).show();

    }
}

public String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    try {
        String[] proj = { MediaStore.Images.Media.DATA };
        cursor = context.getContentResolver().query(contentUri,  proj, null, null, null);
        int column_index =  cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
}

I am getting null when I display in TOAST. I am running Lollipop. Please could someone explain in detail on how to do this. I am able to get the URI without any problems but my only issue is to not being able to convert it to a real path to store in my database.

Thanks

This problem occurs mainly for google native devices such as Nexus because in these devices the only image library is google photos. In google photos you get to choose not only those images which are present on your device but also those photos which are stored on cloud storage too. Try the below mentioned updated code of yours and let me know if it worked or not. Your intent should have action as Intent.ACTION_GET_CONTENT

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == ATTACHMENT_PHOTO_GALLERY && resultCode == RESULT_OK && null != data) {
        Uri selectedImage = data.getData();
        nameView.setText(selectedImage.toString());
        String realPath = getRealPathFromURI(this, selectedImage);
        Toast.makeText(MainActivity.this, realPath, Toast.LENGTH_LONG).show();

    }
}

public String getRealPathFromURI(Context context, Uri contentUri) {
    Cursor cursor = null;
    String path = null;
    try {
        String[] proj = {MediaStore.Images.Media.DATA};
        cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        path = cursor.getString(column_index);
    } finally {
        if (cursor != null) {
            cursor.close();
        }
    }
    //The above code will fail to get file path if the file is selected from google photos.
    //Then this will be the alternative approach
    if (path == null && contentUri.toString().startsWith("content://com.google.android.apps.photos.content")) {
        Bitmap requiredImage = null;
        //Below key should be used for saving the newly downloaded image path as 
        //photoIdentificationKey as Key parameter and newly generated path as Value.
        //An additional check should be implemented on your storage that whether any local
        //path exists for corresponding photoIdentificationKey, if yes then use the existing
        //local path else download new image.
        String photoIdentificationKey = Uri.parse(contentUri.getLastPathSegment()).getLastPathSegment();
        BitmapFactory.Options options = new BitmapFactory.Options();
        InputStream inputStream;

        try {
            inputStream = getApplication().getContentResolver().openInputStream(contentUri);
            requiredImage = BitmapFactory.decodeStream(inputStream, null, options);

            //Save the newly downloaded image to your isolated storage and return the path
            //on which this new image has been saved.

            inputStream.close();
            path = saveAndReturnPathForSavedImage(requiredImage);
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
    return path;
}

private String saveAndReturnPathForSavedImage(Bitmap bmp) {
    String path = Environment.getExternalStorageDirectory().toString();
    OutputStream out = null;
    File file = new File(path, "IMAGE"+ Calendar.getInstance().getTime()+".jpg"); // the File to save to
    try {
        out = new FileOutputStream(file);
        bmp.compress(Bitmap.CompressFormat.PNG, 100, out);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            if (out != null) {
                out.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return file.getPath();
}

If your Intent data data is not null then you can try this. I've used this code to get image path from gallery, and its working in all devices.

  Uri selectedImage = data.getData();
                        String[] filePath = {MediaStore.Images.Media.DATA};
                        Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
                        c.moveToFirst();
                        int columnIndex = c.getColumnIndex(filePath[0]);
                        String picturePath = c.getString(columnIndex);

                        c.close();
                        Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));

Log.e("path of image from gallery......******************.........", picturePath + "");

Note: Be sure your data should not be null otherwise it will give NullPointerException .

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