get real path from android URI after selecting image from gallery Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of get real path from android URI after selecting image from gallery without wasting too much if your time.

The question is published on by Tutorial Guruji team.

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

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;
}
We are here to answer your question about get real path from android URI after selecting image from gallery - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji