2012-01-16 10 views
34

Vui lòng tìm mã của tôi bên dưới. Tôi cần lấy đường dẫn tệp của tài liệu pdf, được người dùng chọn từ SDcard. Vấn đề là các URI.getPath() trả về:Cách lấy đường dẫn tệp từ URI?

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

Con đường đúng là:

/sdcard/my Report.pdf 

Xin lưu ý mà tôi đã tìm kiếm trên stackoverflow nhưng thấy các ví dụ về nhận filepath hình ảnh hoặc video, không có ví dụ về cách lấy filepath trong trường hợp PDF?

Mã của tôi, không phải tất cả các mã nhưng chỉ có một phần pdf:

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"); 
      }    
      } 
     } 
} 

thể một số xin vui lòng giúp tôi làm thế nào để có được đường dẫn chính xác từ URI?

+0

Dưới đây là câu trả lời đúng cho câu hỏi [có một cái nhìn] [1] [1]: http://stackoverflow.com/questions/3401579/get-filename-and-path-from-uri-from-mediastore – sheetal

Trả lời

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

nên trả lại u con đường đúng

EDIT

Như @Tron gợi ý đoạn code làm việc là

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

Tôi không có FILE ở đây, tôi cần lấy nó từ Uri. –

+0

xem câu trả lời được chỉnh sửa –

+0

Quay trở lại: /content:/com.quickoffice.mx.samsung/file%3A%2F%2F%2Fmnt%2Fsdcard%2FMy%2520Report.pdf/My%20Report.pdf?MIME-TYPE= ứng dụng% 2Fpdf –

4

Dưới đây là câu trả lời cho câu hỏi here

Trên thực tế chúng ta phải có được nó từ ContentProvider thể chia sẻ Camera Application