When does SQLiteOpenHelper onCreate / onUpgrade run?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
SQLiteOpenHelper is a crucial part of database management in Android development. It simplifies the process of creating, opening, and upgrading databases. The two key lifecycle methods within `SQLiteOpenHelper` that a developer should be aware of are `onCreate()` and `onUpgrade()`. Understanding when and how these methods are invoked is fundamental to managing database schemas and data efficiently.
Understanding `SQLiteOpenHelper`
`SQLiteOpenHelper` is an abstract class provided by Android that helps manage database creation and version management. You don't use it directly; instead, you subclass it to handle database operations. Upon subclassing, there are three abstract methods you typically override:
- `onCreate(SQLiteDatabase db)`
- `onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)`
- `onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion)`
This article focuses on the first two methods.
When is `onCreate()` Invoked?
The `onCreate()` method is called when the database is created for the first time. This is where the initial setup of the database takes place, such as creating tables and populating them with initial data. It is only executed if the database file did not exist and is created during the current open operation.
Example Usage of `onCreate()`
- Version Number: An integer representing the schema version in the `SQLiteOpenHelper`.
- Upgrade Logic: If the version number you specify in the constructor is higher than the version stored in the database file, `onUpgrade()` is called.

