[android] How to get the file path from URI?

Please find my code below. I need to get the file path of the pdf document, selected by the user from SDcard. The issue is that the URI.getPath() returns:

/file:///mnt/sdcard/my%20Report.pdf/my Report.pdf

The correct path is:

/sdcard/my Report.pdf

Please note that i searched on stackoverflow but found the example of getting the filePath of image or video, there is no example of how to get the filepath in case of PDF?

My code , NOT all the code but only the pdf part:

 public void openPDF(View v)
 {
     Intent intent = new Intent();
     //intent.setType("pdf/*");
     intent.setType("application/pdf");
     intent.setAction(Intent.ACTION_GET_CONTENT);
     startActivityForResult(Intent.createChooser(intent, "Select Pdf"), SELECT_PDF_DIALOG);
 }
 public void onActivityResult(int requestCode, int resultCode, Intent result) 
 {
     if (resultCode == RESULT_OK) 
     {
         if (requestCode == SELECT_PDF_DIALOG) 
         {
             Uri data = result.getData();
             if(data.getLastPathSegment().endsWith("pdf"))
             {
                String pdfPath = data.getPath();
             } 
             else 
             {
                 CommonMethods.ShowMessageBox(CraneTrackActivity.this, "Invalid file type");   
             }               
          }
      }
 }

Can some please help me how to get the correct path from URI?

This question is related to android pdf uri filepath

The answer is


Here is the answer to the question here

Actually we have to get it from the sharable ContentProvider of Camera Application.

EDIT . Copying answer that worked for me

private String getRealPathFromURI(Uri contentUri) {
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(mContext, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;

}


File myFile = new File(uri.toString());
myFile.getAbsolutePath()

should return u the correct path

EDIT

As @Tron suggested the working code is

File myFile = new File(uri.getPath());
myFile.getAbsolutePath()

Examples related to android

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How to implement a simple scenario the OO way My eclipse won't open, i download the bundle pack it keeps saying error log getting " (1) no such column: _id10 " error java doesn't run if structure inside of onclick listener Cannot retrieve string(s) from preferences (settings) strange error in my Animation Drawable how to put image in a bundle and pass it to another activity FragmentActivity to Fragment A failure occurred while executing com.android.build.gradle.internal.tasks

Examples related to pdf

ImageMagick security policy 'PDF' blocking conversion How to extract table as text from the PDF using Python? Extract a page from a pdf as a jpeg How can I read pdf in python? Generating a PDF file from React Components Extract Data from PDF and Add to Worksheet How to extract text from a PDF file? How to download PDF automatically using js? Download pdf file using jquery ajax Generate PDF from HTML using pdfMake in Angularjs

Examples related to uri

Get Path from another app (WhatsApp) What is the difference between resource and endpoint? Convert a file path to Uri in Android How do I delete files programmatically on Android? java.net.MalformedURLException: no protocol on URL based on a string modified with URLEncoder How to get id from URL in codeigniter? Get real path from URI, Android KitKat new storage access framework Use URI builder in Android or create URL with variables Converting of Uri to String How are parameters sent in an HTTP POST request?

Examples related to filepath

Anaconda / Python: Change Anaconda Prompt User Path How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax? How do I get the file name from a String containing the Absolute file path? Get the filePath from Filename using Java Directory.GetFiles: how to get only filename, not full path? Getting current directory in .NET web application Extract a part of the filepath (a directory) in Python Check whether a path is valid in Python without creating a file at the path's target How to get the file path from URI? File path issues in R using Windows ("Hex digits in character string" error)