質問

I've noticed that there are several question on this exception. But they do not solve my problem.

I have a databaseHelper class that has a inner class that extends SQLiteOpenHelper:

private static class OpenHelper extends SQLiteOpenHelper {
          OpenHelper(Context context) {
             super(context, DATABASE_NAME, null, DATABASE_VERSION);
          }

          @Override
          public void onCreate(SQLiteDatabase db) {
             db.execSQL("CREATE TABLE " + TABLE_NAME + "(id INTEGER PRIMARY KEY, name TEXT)");
          }
          @Override
          public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
             Log.w("DBHELPER", "Upgrading database");
             db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME);

             onCreate(db);
          }


      }

I have a service that updates the db continuously. And a activities that fetches data from the db .

In both the service and the activities the dbHelper get created:

this.dh = new DatabaseHelper(this);

And I do get the DatabaseObjectNotClosedException. Do I need to close the DatabaseHelper? How would I do that? Or how do I solve this problem?

役に立ちましたか?

解決

This is something that needs to be taken care of outside of your SQLiteOpenHelper.

You need to close your database connection anytime your activity or service is paused/stopped. If you don't do this, Android will throw that exception you keep seeing in LogCat.

The best practice for this depends on whether you have a global or local DB object.

Local
Use a try catch finally block. Open your database in the try, and then close it in finally. That way no matter if there was an error or not, your database is closed.

OpenHelper dh = new DatabaseHelper(this);
SQLiteDatabase db = null;
try {
    db =  dh.getWritableDatabase();
} catch(SQLiteException e){

} finally {
    if(db != null && db.isOpen())
        db.close();
}

Global
Utilize the Android lifecycle to manage your database. Open the database in onResume, and close it in 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();
    }
}

As for your Service issue. Read up on the Service Lifecycle. You can use the pattern I implemented in the Global section there.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top