Android/SQLite FAQ: I’ve created an instance of a SQLiteOpenHelper object, but the
onCreate method isn’t getting called, what's wrong? (
onCreate is not getting called, and my database tables are not being created.)
There are a couple of possible problems here, but as I found out, the first thing to know is that just calling the constructor for your SQLiteOpenHelper class isn’t enough to have the
onCreate method called. In fact,
onCreate won't be called at all unless you call the
getReadableDatabase methods on your SQLiteOpenHelper class, like this:
myHelper.getWritableDatabase(); // or this myHelper.getReadableDatabase();
It took me a little while to understand this, but
onCreate isn't called from your constructor; it’s called by the Android framework when you try to access your database.
Your database must not exist
That's the basic problem I see most Android developers run into, but there is a second problem you also need to know about: If your database already exists, the
onCreate method will never be called.
As its named implies, the
onCreate method is only called when the database needs to be created. You can get a little glimpse of this from the SQLiteOpenHelper onCreate method documentation:
onCreateis) called when the database is created for the first time. This is where the creation of tables and the initial population of the tables should happen.
I just ran into this problem when developing the first Android app I've worked on in the last year or so. I had already sent my app (and database) to my Android emulator, and then needed to add a new table to my database. I kept trying to get my new database to be created from the
onCreate method, but because the database already existed,
onCreate was never called.
Fixing this onCreate "database must not exist" problem
The fix for this second problem is to delete your database. You can do this by manually deleting your database using the
adb shell command, where you log into the shell and then use the
rm command to delete your database file.
Or, you can do what I did, and just uninstall your app from the Android emulator. This removes not only the app, but your database as well.
In summary, I hope these “SQLiteOpenHelper onCreate method not creating my database” tips have been helpful.