如何避免在SQLiteDatabase中从未在数据库上显式调用“close()”

时间:2012-10-24 13:53:09

标签: android sqlite

  

可能重复:
  Android error - close() was never explicitly called on database

我的Android应用程序出了问题。

我实现了一个单例,它有一个带有以下代码的方法:

public Cursor getFooCursor(Context context)
{
    StorageDBOpenHelper helper = new StorageDBOpenHelper(context);
    SQLiteDatabase db = helper.getReadableDatabase();

    Cursor c = db.query("Foo", new String[] {"_id", "Titel"}, null, null, null, null, "Test DESC");

    return c;
}

当我使用它时,我有时会收到错误:SQLiteDatabase: close() was never explicitly called on database

如何避免这种情况?问题是,我不能简单地为db.close()生成return c,因为它是空的。

2 个答案:

答案 0 :(得分:2)

客户端应该打开数据库,然后使用此方法获取游标,然后在游标完成时关闭游标和数据库。我建议不要在这里使用单身人士。而是做这样的事情:

public class FooDB
{
    private SQLiteDatabase db = null;

    private void open() throws SQLiteException
    {
        if (db != null)
        {
            throw new SQLiteException("Database already opened");
        }

        // Create our open helper
        StorageDBOpenHelper helper = new StorageDBOpenHelper(context);
        try
        {
            // Try to actually get the database objects
            db = m_openHelper.getWritableDatabase();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

        if (db == null)
        {
            throw new SQLiteException("Failed to open database");
        }
    }

    private void close() throws SQLiteException
    {
        if (db != null)
        {
            db.close();
            db = null;
        }        
    }

    public Cursor getFooCursor(Context context)
    {
        if(db == null)
            throw new SQLiteException("Database not open");    

        Cursor c = db.query("Foo", new String[] {"_id", "Titel"}, null, null, null, null, "Test DESC");

        return c;
    }
}

答案 1 :(得分:2)

我使用的方法是将db的实例传递给返回cursor的类:

StorageDBOpenHelper helper = new StorageDBOpenHelper(context);
SQLiteDatabase db = helper.getReadableDatabase();

public Cursor getFooCursor(Context context, SQLiteDatabase db ) {
      Cursor c = db.query("Foo", new String[] {"_id", "Titel"}, null, null, null,
 null, "Test DESC");
      return c;
 }

db.close();