SQLite CursorWindow限制 - 如何避免崩溃

时间:2017-08-14 15:12:38

标签: android sqlite android-cursor

我必须执行查询并将结果存储在列表中,我使用的函数如下:

List<SpoolInDB> getSpoolInRecords(String label, boolean getLastInserted) {
    List<SpoolInDB> spoolInList = new ArrayList<>();
    try {
        if (mdb == null)
            mdb = mdbHelper.getWritableDatabase();

        SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
        qb.setTables(TABLE_SPOOLIN);

        Cursor c = qb.query(mdb, null, " label='" + label + "'", null, null, null, " dateins " + (getLastInserted ? "desc" : "asc"));
        if (c != null) {
            c.moveToFirst();
            if (c.getCount() > 0) {
                int ndxid = c.getColumnIndex("id");
                int ndxserverID = c.getColumnIndex("serverID");
                int ndxlabel = c.getColumnIndex("label");
                int ndxvalue = c.getColumnIndex("value");
                int ndxpriority = c.getColumnIndex("priority");
                int ndxdateins = c.getColumnIndex("dateins");

                do {
                    SpoolInDB spoolIn = new SpoolInDB();
                    spoolIn.setId(c.getString(ndxid));
                    spoolIn.setServerID(c.getString(ndxserverID));
                    spoolIn.setLabel(c.getString(ndxlabel));
                    spoolIn.setValue(c.getString(ndxvalue));
                    spoolIn.setPriority(c.getString(ndxpriority));
                    spoolIn.setDateins(c.getString(ndxdateins));
                    spoolInList.add(spoolIn);

                } while (c.moveToNext());
            }
            c.close();
        }
    } catch (Exception e) {
        wil.WriteFile("4)DbGest - Exception: " + e.toString());
    }
    return spoolInList;
}

在正常情况下,此函数可以正常工作,但在某些情况下,此函数会产生异常:

Window is full: requested allocation 3209815 bytes, free space 2096647 bytes, window size 2097152 bytes

这个问题出现了,因为在&#34;值&#34;字段我可以存储json数据,在某些情况下可能大于2mb,我无法预测当数据大于2mb时,我需要一个始终有效的解决方案。

我如何解决我的问题?

1 个答案:

答案 0 :(得分:2)

CursorWindow大小限制为2MB(截至目前)。您无法读取大小超过2MB的单行,因为无法将其放在Cursor中。

因此,您可以将其解析并存储在数据库中的单独列或表中,而不是将整个JSON存储为单个元素。

那样,

  1. 您可以将JSON中不需要的数据保存在数据库中。
  2. 您可以一次查询部分数据(少数列),以便查询的数据不会超过2MB CursorWindow限制。
  3. 或者你可以尝试其他数据库系统,比如Realm(我还没试过,所以我不确定那里是否有任何限制)。