Reopening database after onpause

68 Views Asked by At

I am new to android programming and am just starting to dabble in using a sqlite database. In my app, I am closing the database at onpause and ondestroy.

However, when using the app, I am attempting to reopen the database/app after closing it for a short while, but kept having an error 'unable to open an already closed database'?

Please help. Here is the excerpt of the java file;

public class Apple extends Activity {

DbA myDb;   

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.apple_layout);
    openDB();
    }

  private void openDB() {
myDb= new DbA(this);
myDb.open();
}

  @Override 
  protected void onDestroy() {
super.onDestroy();  
myDb.close();
  }


  @Override
  protected void onResume() {
super.onResume();
myDb.open();
 }

  @Override
 protected void onPause() {
super.onPause();        
myDb.close();   
  }

Please tell me what I'm doing wrong.

1

There are 1 best solutions below

0
On

In my opinions there's no need to keep an open database connection the whole lifecycle of the activity.

I usually get writable database when I'm going to perform an action and close when it finish.

For example, to add records, you can have the following method

public void addItem(Item item) {
    if (item == null) {
        return;
    }

    // get writable database and begin transaction
    final SQLiteDatabase database = dbHelper.getWritableDatabase();
    database.beginTransaction();

    // INSERT ITEM IN DATABASE

    // End transaction and close connection
    database.setTransactionSuccessful();
    database.endTransaction();
    database.close();
}