微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java – Cursor.moveToNext错误

我偶尔会看到一个崩溃报告:

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就需要返回数据源并获得下一个结果窗口.如果在进行此项工作时数据发生了重大变化(例如,现在少于1127行),我可以看到您遇到此类问题.

我建议你:

>限制返回到所需子集的列,以及
>在循环期间避免I / O(例如,旋转Cursor以构建ArrayList< Pair>或其他东西,关闭Cursor,然后迭代列表)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐