2017-05-04 80 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()时提供的值。它只用于识别该结果是针对同一个查询。 –