如何避免"close() was never explicitly called on database in SQLiteDatabase"



可能的重复:
Android错误 - Close()从未在数据库上明确调用

我在我的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,因为它是空的。

我使用的方法是将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();

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

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;
    }
}

相关内容

最新更新