Android: How to close a cursor that returns from Class to Activity

白昼怎懂夜的黑 提交于 2019-12-13 05:27:20

问题


I have: Accounts.java

public class Accounts{

    private SQLiteDatabase dbConfig;

public Cursor list(Context context, String db, String where, String order) {

    DBHelper dbHelper = new DBHelper(context, db);
    dbConfig = dbHelper.getReadableDatabase();

    Cursor c = dbConfig.query("accounts", new String[]{ "iId","sName"}, where, null, null, null, order);
    return c;   
    }
}

and: MainActivity.java

Accounts account = new Accounts();
Cursor cursor =  account.list(getApplicationContext(), globalDB, null, null);
while (cursor.moveToNext()) { 
     int id = cursor.getInt(0);
     String name = cursor.getString(1);
}
cursor.close();

Running my application I get some logcat messages like:

close() was never explicitly called on database...

What is the best way to prevent it? How can I close a Cursor that returns from other class? Thanks


回答1:


After account.list() exits, the underlying database connection is still open, but there are no remaining references to it. So, it has leaked.

You can close the database once you're finished with it, or you can keep it open for the lifetime of your application by having a single global database connection which you open once, share amongst all your activities, and never close.

I recommend the latter approach. It results in much simpler code.




回答2:


instead of calling cursor.close(); you can call and create a Accounts.close() method that closes both cursor and database



来源:https://stackoverflow.com/questions/10962585/android-how-to-close-a-cursor-that-returns-from-class-to-activity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!