读取数据库时Java内存异常

时间:2016-07-07 14:22:50

标签: java android out-of-memory android-sqlite

我正在尝试从数据库中检索数据。但是,在阅读时,我的光标抛出了Java Out of Memory Exception。查看堆栈跟踪,它与字符串构建器有关。我认为将代码移动到一个线程会起作用,但我仍然有例外。以下是无效的代码:

 public Object[] getData() {
    CustomRunnable runnable = new CustomRunnable();
    Thread runThread = new Thread(runnable);
    runThread.start();
    while ((runThread.getState() != Thread.State.TERMINATED)) {
    }
    return runnable.getDBlist().toArray();
}

public class CustomRunnable implements Runnable {

    List<String> dbList;
    public boolean done = false;

    @Override
    public void run() {
        dbList = new ArrayList<>();
        SQLiteDatabase sqLiteDatabase = getWritableDatabase();
        String query = "SELECT * FROM " + TABLE_ITEMS + " WHERE 1";
        //Cursor code
        Cursor c = sqLiteDatabase.rawQuery(query, null);
        c.moveToFirst();
        String dbString = "";
        while (!c.isAfterLast()) {
            if (c.getString(c.getColumnIndex(COLUMN_ITEMNAME)) != null) {
                dbString += c.getString(c.getColumnIndex(COLUMN_ITEMNAME));
            }
        /*
        if(c.getString(c.getColumnIndex(COLUMN_COST))!=null){
            dbString+=c.getString(c.getColumnIndex(COLUMN_COST));
        }
        */
            dbList.add(dbString);
        }
        c.close();
        sqLiteDatabase.close();
        done = true;
    }

    public List<String> getDBlist() {
        return dbList;
    }
}

这是我的堆栈跟踪:

java.lang.OutOfMemoryError: Failed to allocate a 83410 byte allocation with 71348 free bytes and 69KB until OOM
                                                                    at java.lang.AbstractStringBuilder.enlargeBuffer(AbstractStringBuilder.java:95)
                                                                    at java.lang.AbstractStringBuilder.append0(AbstractStringBuilder.java:146)
                                                                    at java.lang.StringBuilder.append(StringBuilder.java:216)
                                                                    at com.daita.ereciept.DBHandler.getData(DBHandler.java:62)
                                                                    at com.daita.ereciept.MainActivity$1.run(MainActivity.java:37)
                                                                    at java.lang.Thread.run(Thread.java:818)

1 个答案:

答案 0 :(得分:0)

您需要将JVM堆大小作为第一个选项进行故障排除。如果你确定你没有错。

我的意思是错误的......你知道没有多少数据可以引起我的兴趣。你在内存中需要这么多数据。