8

When I am trying to insert to data base log cat shows an error like java.lang.illegalstateexception database not open android.

But I have opened the db using

   db = SQLiteDatabase.openDatabase(DATABASE_PATH, null,
                SQLiteDatabase.OPEN_READWRITE);

The error is not occurring frequently.Anybody know the reason for this?

Padma Kumar
  • 19,893
  • 17
  • 73
  • 130
user1414146
  • 209
  • 1
  • 4
  • 9

4 Answers4

13

Try it like this:

  if (!db.isOpen()) {
       db = getApplicationContext().openOrCreateDatabase(DATABASE_PATH, SQLiteDatabase.OPEN_READWRITE, null);
     }
Simon Dorociak
  • 33,374
  • 10
  • 68
  • 106
  • I tried this but instead of getApplicationContext() I have added SQLiteDatabase.How will get applicationcontext in a class extended from SQLiteOpenHelper – user1414146 May 29 '12 at 11:20
  • 1
    so contructor of your `SQLiteOpenHelper` takes one parameter `Context context` so `context.openOrCreateDatabase()` ... – Simon Dorociak May 29 '12 at 11:25
2

try

DatabaseHelper dataHelper;
SQLiteDatabase mDb;
    public DbManager openDB() throws SQLException {

    mDb = dataHelper.getWritableDatabase();
    return this;
}

and call this method where your re writing your current code.

GAMA
  • 5,958
  • 14
  • 79
  • 126
0

Try this code

 public class DataBaseHelper extends SQLiteOpenHelper{
    public SQLiteDatabase openDataBase() throws SQLException{

            //Open the database

            File dbFile = _myContext.getDatabasePath( DB_PATH + DB_NAME ); 
            _myDataBase = SQLiteDatabase.openDatabase(dbFile.toString(), null, SQLiteDatabase.OPEN_READWRITE);

            return _myDataBase;
        }//end of openDataBase() method
}
AndroidLearner
  • 657
  • 5
  • 10
-1

maybe you are opening an opened Database. close your database every time your work is done.

Bob
  • 22,810
  • 38
  • 143
  • 225