内存的分配游标时 [英] Out of Memory when allocating cursors
问题描述
我有,我不能想出一个内存问题。我有一个类,做我的所有数据库中检索工作。我的错误是:
I have a memory problem that I can't figure out. I have one class that does all my database retrieving work. The error I have is the following:
android.database.CursorWindowAllocationException: Cursor window allocation of 2048 kb failed. # Open Cursors=733 (# cursors opened by this proc=733)
内存分配错误发生时,我这样做:
The memory allocation error occurs when I do this:
mDatabaseInterface.getGraphForLevel(level);
我知道这是一个泄漏,因为我粗略地调用这个方法每2.5秒,5或6首先调用通过轻松。现在,这里是我的DatabaseInterface类中的方法:
I know it's a leak because I call this method every 2.5 seconds roughly, and the 5 or 6 first calls go through easily. Now here are the methods in my DatabaseInterface class:
public Graph getGraphForLevel(Level level) {
//get the nodes
ArrayList<Node> nodes = new ArrayList<Node>(Arrays.asList(this.getNodesWithLevel(level)));
//get the edges
ArrayList<Edge> edges = new ArrayList<Edge>(Arrays.asList(this.getEdgesWithNodes(nodes)));
return new Graph(nodes, edges);
}
public Node[] getNodesWithLevel(Level level) {
List<Node> l = new ArrayList<Node>();
Cursor cursor = mDatabase.query("nodes", null,
"level = " + wrapSql(String.valueOf(level.getId())), null, null, null, null);
while (cursor.moveToNext()) {
l.add(parseNodeFromCursor(cursor));
}
cursor.close();
return l.toArray(new Node[l.size()]);
}
private Node parseNodeFromCursor(Cursor cursor) {
Level l = getLevelWithId(cursor.getInt(2));
return new Node(cursor.getInt(0), cursor.getString(1), l,
cursor.getInt(4), cursor.getInt(5));
}
我有很多的相互调用的方法,但我知道这是不是一个递归问题,因为这类作品在另一个应用程序。我的主要问题是,为什么不 cursor.close()
解放光标?如果我是这样的:
I have a lot of methods that call each other but I know it's not a recursion problem because this class works in another app. My main question is why doesn't cursor.close()
liberate the cursor? If I do something like:
cursor = mDatabase.query(...);
cursor.moveToNext();
Node node = new Node(cursor.getInt());
cursor.close();
时光标保留在这种情况下?
Is the cursor retained in that case?
在此先感谢。
推荐答案
到调用cursor.close()
应该在最后
块中,以防你遍历它,当一个异常被抛出。
The call to cursor.close()
should be in a finally
block in case an exception is thrown while you're iterating over it.
Cursor cursor = mDatabase.query("nodes", null,
"level = " + wrapSql(String.valueOf(level.getId())), null, null, null, null);
try {
while (cursor.moveToNext()) {
l.add(parseNodeFromCursor(cursor));
}
} finally {
cursor.close();
}
这篇关于内存的分配游标时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!