我想从URI
中检索视频的真实路径我使用 startActivityForResult
startActivityForResult(
Intent.createChooser(
new Intent(Intent.ACTION_GET_CONTENT)
.setType("video/*"), "Choose Video"),
REQUEST_VIDEO
);
我正在 onActivityResult
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
if(requestCode == REQUEST_VIDEO){
Uri uri = data.getData();
String realpath = getRealPathFromURI(getContext(),uri);
}
}
getRealPathFromUri
就是这样;
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
但是realpath总是返回null;
我搜索但仍然返回null
它与sdk_version有关吗?
或是否已将MediaStore.Images.Media.DATA
更改为MediaStore.Video.Media.DATA
?
我被困在这里,毫无头绪,善意地建议!任何帮助都将非常有价值
- !谢谢
答案 0 :(得分:1)
试试这个,
public static String getRealVideoPathFromURI(ContentResolver contentResolver,
Uri contentURI) {
Cursor cursor = contentResolver.query(contentURI, null, null, null,
null);
if (cursor == null)
return contentURI.getPath();
else {
cursor.moveToFirst();
int idx = cursor.getColumnIndex(Video.VideoColumns.DATA);
try {
return cursor.getString(idx);
} catch (Exception exception) {
return null;
}
}
}
答案 1 :(得分:0)
获得Uri
后,您可以通过以下方式获取绝对文件路径:
File myFile = new File(uri.getPath());
myFile.getAbsolutePath();
答案 2 :(得分:0)
据我了解,获取“真实”文件路径的方式取决于Android的SDK版本。
方案1)我在模拟器上运行 targetSdkVersion 28 ,并且可以通过onActivityResult
中的此简单命令获取“真实”文件路径:
data.getData().getPath();
方案2)但是在我的物理设备 SDK 25级中,我得到的正是您所显示的内容路径或类似内容。
content://media/external/file/3131
“真实”文件路径在哪里:
/storage/emulated/0/Download/lista_produtos.xlsx
为了获得物理设备中的“真实”文件路径并考虑模拟器,我在onActivityResult
内使用了这段代码:
Uri uri = data.getData();
String realPath;
if (DocumentsContract.isDocumentUri(getApplicationContext(), uri)) {
String[] path = uri.getPath().split(":");
realPath = path[1];
Log.i("debinf ProdAct", "Real file path on Emulator: "+realPath);
} else {
CursorLoader cursorLoader = new CursorLoader(getApplicationContext(), uri, null, null, null,null);
Cursor cursor = cursorLoader.loadInBackground();
int idx = cursor.getColumnIndex(MediaStore.Files.FileColumns.DATA);
cursor.moveToFirst();
realPath = cursor.getString(idx);
Log.i("debinf ProdAct", "Real file path in physical device "+realPath);
cursor.close();
}
我想在您的情况下,更合适的索引是:
int idx = cursor.getColumnIndex(MediaStore.Video.Media.DATA);
我希望对您有所帮助,因为我没有使用您的代码。正如我之前所说,这取决于Android的SDK版本。
答案 3 :(得分:0)
我想您尚未授予读写外部存储权限的权限。我有同样的问题,授予权限并没有解决它。谁知道,它能解决您的问题!