游标 returns id= 0 如果文件夹有 1 个元素,XML 文件
Cursor returns id= 0 if folder has 1 element, XML file
我尝试使用 Cursor 查找创建的 XML 文件的 content:// 地址。
我使用以下代码执行此操作:
public static String xmlFilePath = Environment.getExternalStorageDirectory() + "/" + WiFiTransferService.FileServerAsyncTask.context.getPackageName()+ "/" + "variables" + ".xml";
Cursor cursor = getContentResolver().query(
mFilesUri,
new String[]{MediaStore.Files.FileColumns._ID},
MediaStore.Files.FileColumns.DATA + "=?",
new String[]{xmlFilePath}, null);
if (cursor != null && cursor.moveToFirst()) {
id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Files.FileColumns._ID));
}
if (cursor != null) {
cursor.close();
}
问题是当我在文件夹中有一个文件时我得到 0 id,当我有 2 个或更多文件时得到正确的 id(例如 3268)。非常奇怪的行为,我不知道是什么原因造成的。
问题解决了!我在程序中创建了文件并将其存储在 SD 卡上,一切正常,但设备没有更新其数据库 (DB)。当我手动将此文件复制到 phone 时,所有内容都会添加。
所以我需要做的是使用以下代码以编程方式将刚刚创建的文件添加到我的 phone 数据库中:
ContentValues values = new ContentValues();
values.put(MediaStore.Files.FileColumns.TITLE,
FilenameUtils.getBaseName(xmlFilePath));
values.put(MediaStore.Files.FileColumns.MIME_TYPE, "text/*");
values.put("_data", xmlFilePath);
getContentResolver().insert(MediaStore.Files.getContentUri("external"), values);
当然你必须在Cursor开始之前添加它。有问题的代码写得很好,只是需要更新数据库。
希望它能帮助避免此类错误并展示如何正确提取 XML 文件内容:// 路径。
我尝试使用 Cursor 查找创建的 XML 文件的 content:// 地址。
我使用以下代码执行此操作:
public static String xmlFilePath = Environment.getExternalStorageDirectory() + "/" + WiFiTransferService.FileServerAsyncTask.context.getPackageName()+ "/" + "variables" + ".xml";
Cursor cursor = getContentResolver().query(
mFilesUri,
new String[]{MediaStore.Files.FileColumns._ID},
MediaStore.Files.FileColumns.DATA + "=?",
new String[]{xmlFilePath}, null);
if (cursor != null && cursor.moveToFirst()) {
id = cursor.getInt(cursor
.getColumnIndex(MediaStore.Files.FileColumns._ID));
}
if (cursor != null) {
cursor.close();
}
问题是当我在文件夹中有一个文件时我得到 0 id,当我有 2 个或更多文件时得到正确的 id(例如 3268)。非常奇怪的行为,我不知道是什么原因造成的。
问题解决了!我在程序中创建了文件并将其存储在 SD 卡上,一切正常,但设备没有更新其数据库 (DB)。当我手动将此文件复制到 phone 时,所有内容都会添加。
所以我需要做的是使用以下代码以编程方式将刚刚创建的文件添加到我的 phone 数据库中:
ContentValues values = new ContentValues();
values.put(MediaStore.Files.FileColumns.TITLE,
FilenameUtils.getBaseName(xmlFilePath));
values.put(MediaStore.Files.FileColumns.MIME_TYPE, "text/*");
values.put("_data", xmlFilePath);
getContentResolver().insert(MediaStore.Files.getContentUri("external"), values);
当然你必须在Cursor开始之前添加它。有问题的代码写得很好,只是需要更新数据库。
希望它能帮助避免此类错误并展示如何正确提取 XML 文件内容:// 路径。