Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 504
Yaqub Ahmad Avatar asked Jan 16 '12 19:01

Yaqub Ahmad


People also ask

How do you find the absolute path of URI?

Uri uri = data. getData(); File file = new File(uri. getPath());//create path from uri final String[] split = file. getPath().

How do I get file path in Android 10?

String path = uri. getPath(); File dir = new File(sdcard. getAbsolutePath()+"/"+path1);

How do I find the file path in Kotlin?

From what I know you can find the path of a file in the internal storage with java simply by using: String path = context. getFilesDir(). getAbsolutePath(); File file = new File(path + "/filename");


1 Answers

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() 
like image 69
Seshu Vinay Avatar answered Sep 29 '22 17:09

Seshu Vinay