gpt4 book ai didi

Android - 如何从文档中获取选定的文件名

转载 作者:IT老高 更新时间:2023-10-28 23:03:22 27 4
gpt4 key购买 nike

我正在使用以下代码启动选择文档网的 Intent 。

private void showFileChooser() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);

try {
startActivityForResult(
Intent.createChooser(intent, "Select a File to Upload"), 1);
} catch (android.content.ActivityNotFoundException ex) {
// Potentially direct the user to the Market with a Dialog
Toast.makeText(this, "Please install a File Manager.",
Toast.LENGTH_SHORT).show();
}
}

在我试图获取文件路径时,在 onActivity 结果中,它会给出一些其他数字来代替文件名。

    @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
File myFile = new File(uri.toString());
String path = myFile.getAbsolutePath();
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}

我得到这样的路径值。“内容://com.android.providers.downloads.documents/document/1433”但我想要真正的文件名,如 doc1.pdf 等。如何获得它?

最佳答案

当您获得 content://uri 时,您需要查询内容解析器,然后获取显示名称。

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case 1:
if (resultCode == RESULT_OK) {
// Get the Uri of the selected file
Uri uri = data.getData();
String uriString = uri.toString();
File myFile = new File(uriString);
String path = myFile.getAbsolutePath();
String displayName = null;

if (uriString.startsWith("content://")) {
Cursor cursor = null;
try {
cursor = getActivity().getContentResolver().query(uri, null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (uriString.startsWith("file://")) {
displayName = myFile.getName();
}
}
break;
}
super.onActivityResult(requestCode, resultCode, data);
}

关于Android - 如何从文档中获取选定的文件名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24322738/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com