文档

android_database_sqlite_DatabaseObjectNotClosedException

更新时间:

问题分析

在打开数据库操作之前,应用程序没有关闭游标或数据库对象。

解决方案

应用程序没有关闭游标或数据库对象导致抛出此类异常。通过对游标及数据库对之前打开的数据库对象调用close方法进行关闭操作即可。

代码示例

  android.database.sqlite.DatabaseObjectNotClosedException:Application did not close the cursor or database object that was opened here
  android.database.sqlite.DatabaseObjectNotClosedException:Application did not close the cursor or database object that was opened here
    at android.content.ContentResolver.query(ContentResolver.java:399)
    at android.content.ContentResolver.query(ContentResolver.java:316)

操作步骤

1:使用try catch块捕获异常,并在finally部分关闭数据库。

  OpenHelper dh = new DatabaseHelper(this);
  SQLiteDatabase db = null;
  try {
      db =  dh.getWritableDatabase();
  } catch(SQLiteException e){
      e.printStackTrace();
  } finally {
      if(db != null && db.isOpen())
          db.close();
  }

2:在Activity生命周期中,onResume()打开数据库,onPause()关闭数据库。

  OpenHelper dh = null;
  @Override
  protected void onCreate(Bundle savedInstanceState) {
      dh = new DatabaseHelper(this);
  }
  @Override
  protected void onResume() {
      this.db =  dh.getWritableDatabase();
  }
  @Override
  protected void onPause( {
      if(db != null && db.isOpen()){
          db.close();
      }
  }

参考文献

  • 本页导读 (0)
文档反馈