get real path from android URI after selecting image from gallery

Mohammed Sufian picture Mohammed Sufian · Mar 31, 2016 · Viewed 7.1k times · Source

I am ( a beginner android) trying to get the real path (ex: image_name.jpg etc) of Image selected from the gallery by the user.

Here is the code snippet:

 if (requestCode == SELECT_FILE) {
        Uri selectedImage = data.getData();
        Bitmap bitmapImage;
        try {
              bitmapImage =decodeBitmap(selectedImage );
              photoImage = (ImageView) findViewById(R.id.photoImage);
              photoImage.setImageBitmap(bitmapImage);
              photoName = (TextView) findViewById(R.id.designPhoto);
              File thePath = new File(getRealPathFromURI(selectedImage));
              photoName.setText(getRealPathFromURI(selectedImage));
        } catch (Exception e) {
                e.printStackTrace();
        }
 }


 private String getRealPathFromURI(Uri contentURI) {

    String thePath = "no-path-found";
    String[] filePathColumn = {MediaStore.Images.Media.DATA};
    Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null);
    if(cursor.moveToFirst()){
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        thePath = cursor.getString(columnIndex);
    }
    cursor.close();
    return  thePath;
}

but I am not getting anything in the photoName textView also tried lots of codes and guides but with no sucess.

but when I tried it with

photoName.setText(selectedImage.getPath()); 

I am getting

/document/image:n (where n=any numbers) ex:/document/image:147 

but I want a proper file name or path ex: image_name.jpg or /path/image_name.png

trying it from last 3 hours, it would be great if anyone could help me out. humble Thanks in advance.

Answer

Mohammed Sufian picture Mohammed Sufian · Mar 31, 2016

I got it working using

MediaStore.Images.Media.DISPLAY_NAME

updated and working code might help others:

private String getRealPathFromURI(Uri contentURI) {

    String thePath = "no-path-found";
    String[] filePathColumn = {MediaStore.Images.Media.DISPLAY_NAME};
    Cursor cursor = getContentResolver().query(contentURI, filePathColumn, null, null, null);
    if(cursor.moveToFirst()){
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        thePath = cursor.getString(columnIndex);
    }
    cursor.close();
    return  thePath;
}