Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do database schema migrations in Android?

Tags:

Is there a standard way to do database schema migrations on Android? For example, user installs newer version of my Android app but the new version needs to make updates to the database schema (and wiping the user's database and starting over is not an option!). So I need to run some ALTER statements and/or copy tables the first time my new version runs.

like image 400
Eno Avatar asked Mar 21 '10 21:03

Eno


People also ask

What is database migration in Android?

Schema migrations, or database migrations, refer to the management of incremental changes of database schemas. A migration is performed on a database whenever it is necessary to update or revert that database's schema to some newer or older version.

Why should I migrate from SQLite to room database in Android?

The Room persistence library provides a number of benefits over using the SQLite APIs directly: Compile-time verification of SQL queries. Convenience annotations that minimize repetitive and error-prone boilerplate code.


2 Answers

Yes SQLiteOpenHelper has support for migrating between different versions of DB schemas.

Upgrading is done by implementing

public abstract void onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion)

And Rolling back to a previous version is also supported :

public abstract void onDowngrade (SQLiteDatabase db, int oldVersion, int newVersion)
like image 149
Frank Harper Avatar answered Oct 19 '22 15:10

Frank Harper


With a little bit of thought, you can nearly automate a lot of the SQLiteOpenHelper methods. Have a look at this blog post http://www.greenmoonsoftware.com/2012/02/sqlite-schema-migration-in-android/

Update: I ran into some issues if the database updates take a while to complete. Have a look at this blog entry for an implementation that works for me. http://www.greenmoonsoftware.com/2012/05/android-developer-how-to-safely-update-the-application-database/

like image 30
Robert Greathouse Avatar answered Oct 19 '22 15:10

Robert Greathouse