Android SQLiteOpenHelper onCreate() and onUpgrade() Semantics

Overall I’ve been insanely impressed with Android’s documentation.  I’d even go so far to say that the Android platform has the best documentation of any platform or technology I’ve ever learned, including Django and Python.

However, I couldn’t find much on the semantics of the onCreate() and onUpgrade() methods in android.database.sqlite.SQLiteOpenHelper, which is a class that helps you open and upgrade a SQLite database.  I’ll describe below how these methods are called when databases are created and upgraded.

Database Creation

When the SQLite database is constructed for the first time, as you’d expect the onCreate() method is called, creating the tables you’ve defined and executing any other code you’ve written.  However, this method will only be called if the SQLite file is missing in your app’s data directory (/data/data/your.apps.classpath/databases).  This method will not be called if you’ve changed your code and relaunched in the emulator.  If you want onCreate() to run you need to use adb to delete the SQLite database file.  The sqlite3 tool description has more context here.

Database Upgrading

The constructor of your implementation of SQLiteOpenHelper should call the super constructor, passing along the database name and version.  The onUpgrade() method will only be called when the version integer is larger than the current version running in the emulator.  If you want the onUpgrade() method to be called, you need to increment the version number in your code.