38

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?

Yaqub Ahmad
  • 27,569
  • 23
  • 102
  • 149
  • Here is the correct answer to the question [have a look][1] [1]: http://stackoverflow.com/questions/3401579/get-filename-and-path-from-uri-from-mediastore – sheetal Feb 20 '13 at 07:59

2 Answers2

22
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()
Ahmad Dwaik 'Warlock'
  • 5,953
  • 5
  • 34
  • 56
Seshu Vinay
  • 13,560
  • 9
  • 60
  • 109
5

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;
}
Boken
  • 4,825
  • 10
  • 32
  • 42
sheetal
  • 3,014
  • 2
  • 31
  • 45