android.database.CursorWindowAllocationException : Cursor window allocation of 2048 kb failed even after closing cursor

标签 android sqlite memory memory-leaks android-cursor

关于CursorWindowAllocatoinException的SO有很多问题:

他们都建议游标在使用后必须关闭。但这并没有解决我的问题。这是我的代码:

String query = "select serial from tbl1 union select serial from tbl2 union select serial from tbl3";
    SQLiteDatabase db = null;
    Cursor cur = null;
    try {
        SettingsDatabaseHelper dal = new SettingsDatabaseHelper(
                c);
        db = dal.getReadableDatabase();
        cur = db.rawQuery(query, null);
        int numRows = cur.getCount();
        if (numRows > 0) {
            cur.moveToFirst();

            int serialIdx = cur.getColumnIndexOrThrow("serial");
            for (boolean hasItem = cur.moveToFirst(); hasItem; hasItem = cur
                    .moveToNext()) {

                String serial = cur.getString(serialIdx);
                if (Validator.getInstance().isValidSerial(serial))
                    serials.add(serial);

            }
        }
    } finally {
        if (cur != null)
            cur.close();

        if (db != null)
            db.close();
    }

我每隔几秒运行一次这个方法。半小时后,我在 int numRows=cur.getCount(); 中得到 CursorWindowAllocationException 然后我的服务停止。

由于我正在关闭光标,我的 Helper 类可能有问题。代码如下:

public class SettingsDatabaseHelper extends SQLiteOpenHelper {

    private static final String DATABASE_NAME = "mydb.db";
    private static final int DATABASE_VERSION = 1;


    private static final String TBL_CREATE="create table...";



    public SettingsDatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase database) {
        database.execSQL(TBL_CREATE);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        onCreate(db);
    }
}

如何防止这个异常被抛出?

最佳答案

我正在从服务中查询数据库。当我从一个 Activity 中做到这一点时,问题就再也没有发生过。

除了查询之外,我还从同一服务中的串行端口读取数据。也许这导致了问题。但是,当我使用 Activity 而不是服务时,问题再也没有发生过。

关于android.database.CursorWindowAllocationException : Cursor window allocation of 2048 kb failed even after closing cursor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19791059/

相关文章:

android - 在 recyclerview 项目中向上滑动动画

java - 我如何移动到 android 中的新 Activity ?

sqlite - 是什么导致这个 sqlite 外键不匹配?

javascript - 从 IE7 中的 onunload/onbeforeunload 内存中删除 iframe 内容

java - 在 Java 中创建一个非常非常大的 map

java - Android - openCV,获取图像的一部分 - 奇怪的行为

android - 如何在 Android 应用程序中实现 Google 的 DoubleClick Ads?

android - SQLite Android 插入返回 -1

sql - 如何将日期时间值插入 SQLite 数据库?

optimization - 我的Grails应用程序在启动时使用200 MB以上的内存是否正常?