【问题标题】:how to avoid "close() was never explicitly called on database in SQLiteDatabase" [duplicate]如何避免“从未在 SQLiteDatabase 中的数据库上显式调用 close()” [重复]
【发布时间】:2012-10-24 13:53:09
【问题描述】:

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

我的安卓应用有问题。

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

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

如何避免这种情况?问题是,我不能简单地在return c 之前创建一个db.close(),因为那样它是空的。

【问题讨论】:

    标签: android sqlite


    【解决方案1】:

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

    【讨论】:

      【解决方案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;
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-26
        • 1970-01-01
        • 2019-03-09
        • 1970-01-01
        相关资源
        最近更新 更多