2017-05-04 87 views
2

我試圖與Android Studio中的應用程序,可以選擇在SD卡中的文件,並得到其路徑,像一個OpenFileDialog,我已經試過這樣:如何挑選SD卡中的文件?

Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
intent.setType("file/*"); 
startActivityForResult(intent, PICKFILE_REQUEST_CODE); 

但是,這是行不通的,我該怎麼做 ?

+0

參見[這個答案](https://stackoverflow.com/a/30827530/3681880) – Suragch

回答

0

STEP 1 - 使用隱含的意圖:

要選擇從設備中的文件,你應該使用一個implicit Intent

Intent chooseFile = new Intent(Intent.ACTION_GET_CONTENT); 
chooseFile.setType("*/*"); 
chooseFile = Intent.createChooser(chooseFile, "Choose a file"); 
startActivityForResult(chooseFile, PICKFILE_RESULT_CODE); 

第2步 - 獲取文件的絕對路徑:

要從Uri獲取文件路徑,請首先嚐試使用

@Override 
    protected void onActivityResult(int requestCode, int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     Uri uri = data.getData(); 
     String src = uri.getPath(); 
     // this is path of your selected file 
     // if you get error or invalid path try below method and call like getPath(uri); 

    } 

其中數據在onActivityResult().

如果不工作(錯誤或無效URL)的意向返回,使用下面的方法:

public String getPath(Uri uri) { 

    String path = null; 
    String[] projection = { MediaStore.Files.FileColumns.DATA }; 
    Cursor cursor = getContentResolver().query(uri, projection, null, null, null); 

    if(cursor == null){ 
     path = uri.getPath() 
    } 
    else{ 
     cursor.moveToFirst(); 
     int column_index = cursor.getColumnIndexOrThrow(projection[0]); 
     path = cursor.getString(column_index); 
     cursor.close(); 
    } 

    return ((path == null || path.isEmpty()) ? (uri.getPath()) : path); 
} 
+0

上PICKFILE_RESULT_CODE和犯規認識烏里嗨,哥們感謝,但它的錯誤。 – Apptic

+0

即時消息初學者,所以你可以去更多的細節? – Apptic

+0

'PICKFILE_RESULT_CODE'是你的任何整數值 –

0

試試這個:

Intent mediaIntent = new Intent(Intent.ACTION_GET_CONTENT); 
    mediaIntent.setType("*/*"); //set mime type as per requirement 
    startActivityForResult(mediaIntent,0); 

您可以根據需要更改類型。

@Override 
public void onActivityResult(int requestCode, int resultCode, Intent data) { 
    // TODO Auto-generated method stub 
    super.onActivityResult(requestCode, resultCode, data); 
    if (requestCode == 0 
      && resultCode == Activity.RESULT_OK) { 
     Uri uri = data.getData(); 
     Log.d("", "Video URI= " + videoUri); 

    } 
} 
+0

謝謝,但它不承認REQUESTCODE_PICK_VIDEO,它是什麼? – Apptic

+0

我是初學者,所以你可以去更多的細節? – Apptic

+0

我改變了我的答案。這是您在調用startActivityForResult()時提供的值。它只用於識別該結果是針對同一個查詢。 –