我偶尔会看到崩溃报告:
Fatal Exception: java.lang.IllegalStateException: Couldn't read row 1127, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
at android.database.CursorWindow.nativeGetLong(CursorWindow.java)
at android.database.CursorWindow.getLong(CursorWindow.java:511)
at android.database.AbstractWindowedCursor.getLong(AbstractWindowedCursor.java:75)
at android.database.AbstractCursor.moveToPosition(AbstractCursor.java:220)
at android.database.AbstractCursor.moveToNext(AbstractCursor.java:245)
at android.database.CursorWrapper.moveToNext(CursorWrapper.java:166)
at com.anthonymandra.util.ImageUtils.cleanDatabase(SourceFile:381)
显然 moveToNext
在循环中失败(注意第 1127 行)。该循环会删除代表无法再找到的文件的条目。
final ArrayList<ContentProviderOperation> operations = new ArrayList<>();
try( Cursor cursor = c.getContentResolver().query(Meta.CONTENT_URI, null, null, null, null))
{
if (cursor == null)
return;
final int uriColumn = cursor.getColumnIndex(Meta.URI);
final int idColumn = cursor.getColumnIndex(BaseColumns._ID);
while (cursor.moveToNext())
{
String uriString = cursor.getString(uriColumn);
if (uriString == null) // we've got some bogus data, just remove
{
operations.add(ContentProviderOperation.newDelete(
Uri.withAppendedPath(Meta.CONTENT_URI, cursor.getString(idColumn))).build());
continue;
}
Uri uri = Uri.parse(uriString);
UsefulDocumentFile file = UsefulDocumentFile.fromUri(c, uri);
if (!file.exists())
{
operations.add(ContentProviderOperation.newDelete(Meta.CONTENT_URI)
.withSelection(getWhere(), new String[]{uriString}).build());
}
}
}
c.getContentResolver().applyBatch(Meta.AUTHORITY, operations);
知道游标怎么会像那样在循环中失败吗?
最佳答案
您似乎在进行相当大的查询:至少 1127 行,以及所有可能的列(尽管您只使用了其中的两列)。而且,在你使用那个 Cursor
的过程中,您正在执行磁盘 I/O 和/或 IPC 返回到 ContentProvider
,假设 UsefulDocumentFile
与Android的DocumentFile
有关.
正如 Prakash 指出的那样,Cursor
您取回的信息可能仅包含一部分信息。一旦你尝试前进超过那个点,Cursor
需要返回到数据源并获取下一个结果窗口。如果在这项工作进行期间数据发生重大变化(例如,现在少于 1127 行),我可以预见您会遇到此类问题。
我建议你:
将您返回的列限制为您需要的子集,并且
避免循环期间的 I/O(例如,旋转
Cursor
以构建ArrayList<Pair>
或其他东西,关闭Cursor
,然后遍历列表)
关于java - Cursor.moveToNext 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40203198/