[英]ContentResolver - how to get file name from Uri
我用Intent ACTION_GET_CONTENT調用startActivityForResult 。 某些應用程序使用此Uri向我返回數據:
內容://媒體/外部/圖像/媒體/18122
我不知道它是圖像還是視頻還是一些自定義內容。 如何使用ContentResolver從此 Uri 獲取實際文件名或內容標題?
@Durairaj 的回答是針對獲取文件路徑的。 如果您要搜索的是文件的實際名稱(因為您應該使用內容解析,此時您可能會得到很多 content:// URI),您需要執行以下操作:
(代碼從 Durairaj 的回答中復制並修改)
String[] projection = {MediaStore.MediaColumns.DISPLAY_NAME};
Cursor metaCursor = cr.query(uri, projection, null, null, null);
if (metaCursor != null) {
try {
if (metaCursor.moveToFirst()) {
fileName = metaCursor.getString(0);
}
} finally {
metaCursor.close();
}
}
這里要注意的主要部分是我們使用的是MediaStore.MediaColumns.DISPLAY_NAME
,它返回內容的實際名稱。 您也可以嘗試MediaStore.MediaColumns.TITLE
,因為我不確定有什么區別。
您可以通過修改投影從此代碼或任何其他字段獲取文件名
String[] projection = {MediaStore.MediaColumns.DATA};
ContentResolver cr = getApplicationContext().getContentResolver();
Cursor metaCursor = cr.query(uri, projection, null, null, null);
if (metaCursor != null) {
try {
if (metaCursor.moveToFirst()) {
path = metaCursor.getString(0);
}
} finally {
metaCursor.close();
}
}
return path;
要獲取文件名,您可以使用新的DocumentFile格式。
DocumentFile documentFile = DocumentFile.fromSingleUri(this, data.getdata());
String fileName = documentFile.getName();
對於使用 Kotlin 的任何人遇到同樣的問題,您可以定義一個擴展方法來一次性獲取文件名和大小(以字節為單位)。 如果無法檢索字段,則返回 null。
fun Uri.contentSchemeNameAndSize(): Pair<String, Int>? {
return contentResolver.query(this, null, null, null, null)?.use { cursor ->
if (!cursor.moveToFirst()) return@use null
val name = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)
val size = cursor.getColumnIndex(OpenableColumns.SIZE)
cursor.getString(name) to cursor.getInt(size)
}
}
如此使用它
val nameAndSize = yourUri.contentNameAndSize()
// once you've confirmed that is not null, you can then do
val (name, size) = nameAndSize
它可能會引發異常,但它從未對我這樣做過(只要 URI 是有效的content://
URI)。
private static String getRealPathFromURI(Context context, Uri contentUri)
{
String[] proj = { MediaStore.Images.Media.DATA };
CursorLoader loader = new CursorLoader(context, contentUri, proj, null, null, null);
Cursor cursor = loader.loadInBackground();
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
String result = cursor.getString(column_index);
cursor.close();
return result;
}
這是我在閱讀了此處提供的所有答案以及一些 Airgram 在其 SDK 中所做的工作后得出的結論——我在 Github 上開源的一個實用程序:
https://github.com/mankum93/UriUtilsAndroid/tree/master/app/src/main/java/com/androiduriutils
就像調用UriUtils.getDisplayNameSize()
一樣簡單。 它提供內容的名稱和大小。
注意:僅適用於 content:// Uri
這是代碼的一瞥:
/**
* References:
* - https://www.programcreek.com/java-api-examples/?code=MLNO/airgram/airgram-master/TMessagesProj/src/main/java/ir/hamzad/telegram/MediaController.java
* - https://stackoverflow.com/questions/5568874/how-to-extract-the-file-name-from-uri-returned-from-intent-action-get-content
*
* @author Manish@bit.ly/2HjxA0C
* Created on: 03-07-2020
*/
public final class UriUtils {
public static final int CONTENT_SIZE_INVALID = -1;
/**
* @param context context
* @param contentUri content Uri, i.e, of the scheme <code>content://</code>
* @return The Display name and size for content. In case of non-determination, display name
* would be null and content size would be {@link #CONTENT_SIZE_INVALID}
*/
@NonNull
public static DisplayNameAndSize getDisplayNameSize(@NonNull Context context, @NonNull Uri contentUri){
final String scheme = contentUri.getScheme();
if(scheme == null || !scheme.equals(ContentResolver.SCHEME_CONTENT)){
throw new RuntimeException("Only scheme content:// is accepted");
}
final DisplayNameAndSize displayNameAndSize = new DisplayNameAndSize();
displayNameAndSize.size = CONTENT_SIZE_INVALID;
String[] projection = new String[]{MediaStore.Images.Media.DATA, OpenableColumns.DISPLAY_NAME, OpenableColumns.SIZE};
Cursor cursor = context.getContentResolver().query(contentUri, projection, null, null, null);
try {
if (cursor != null && cursor.moveToFirst()) {
// Try extracting content size
int sizeIndex = cursor.getColumnIndex(OpenableColumns.SIZE);
if (sizeIndex != -1) {
displayNameAndSize.size = cursor.getLong(sizeIndex);
}
// Try extracting display name
String name = null;
// Strategy: The column name is NOT guaranteed to be indexed by DISPLAY_NAME
// so, we try two methods
int nameIndex = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
if (nameIndex != -1) {
name = cursor.getString(nameIndex);
}
if (nameIndex == -1 || name == null) {
nameIndex = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
if (nameIndex != -1) {
name = cursor.getString(nameIndex);
}
}
displayNameAndSize.displayName = name;
}
}
finally {
if(cursor != null){
cursor.close();
}
}
// We tried querying the ContentResolver...didn't work out
// Try extracting the last path segment
if(displayNameAndSize.displayName == null){
displayNameAndSize.displayName = contentUri.getLastPathSegment();
}
return displayNameAndSize;
}
}
您可以將 Durairaj 提出的解決方案與以下投影數組一起使用:
String[] projection = { "_data" };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.