When does SQLiteOpenHelper onCreate / onUpgrade run?
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.
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.
Related reading
- When I remove rows in Cassandra I delete only columns not row keys
- When is data consistency not an issue?
- When might 2 phase commit not make progress?
- When should I use a composite index?
- When is it better to use an NSSet over an NSArray?
- When is layoutSubviews called?
- When should I use a NoSQL database instead of a relational database? Is it okay to use both on the same site?
- When should I use CROSS APPLY over INNER JOIN?

System Design Fundamentals
Build a strong foundation in designing scalable, reliable distributed systems.
View the courseTrack what you have practised
A free account saves your progress, solutions and study plan across every problem on Codemia.
System Design practice on Codemia
Work through 120+ system design problems with detailed solutions, from rate limiters to multi-region storage.