jeudi 1 janvier 2015

Android - Trigger manually onCreate method on class derived from SQLiteOpenHelper

I would like to create my database tables on application startup if database is not created so the calls to create tables and insert initial values on these tables are put within OnCreate method in the class that extends SQLiteOpenHelper.


The problem is that on application startup, I do not perform any operation with the database (I only created a new instance of the class that extends SQLiteOpenHelper from my main activity java class) so OnCreate method is not triggered automatically and hence that database is not created.


So in order to trigger onCreate method and force to database be created if it does not exist, once I have created a new instance of the class that extends SQLLiteOpenHelper:



MyDbHelper = new DBHelper(MainActivity.this);


I call below method:



MyDbHelper.SetWritableDb();


which performs the following:



this.getWritableDatabase();


Once above sentece is executed, then OnCreate method is triggered and my database is created through the CREATE statements. Ok, no problem until here.


After creating database tables, I then set some default values to some tables, that is, I perform some inserts but an exception is thrown:



java.lang.IllegalStateException: getDatabase called recursively


I think the problem is that when inserting default values to some tables using below method (this method is called from the class that extends SQLiteOpenHelper):



public final boolean BulkInsert(Context context, DBHelper dbHelper)
{
boolean result = false;

SQLiteDatabase db = dbHelper.getWritableDatabase();

.....
}


getWritableDatabase is called again so database is trying to get blocked again by:



android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked


and then it crashes....


How can I get rid of this? I need my SQLite database to be created (if it is not already created) at main activity when my app starts up.


Aucun commentaire:

Enregistrer un commentaire