This blog tries to be a kind of CPR for code(rs).
Or maybe its the acronym for Code & Practice makes Results.
You decide.

February 19, 2015

Android: onDowngrade... the dark path on databases

So I've been developing an app which has a really big database (for an Android app) and while still in development it has already been upgraded quite a few times.

My team and I have been using the onUpgrade method without any problems for the whole time, but because we use git with one branch per feature and code reviews sometimes the app version that we have installed on our device before when doing a code review is bigger that the one of the next code review.

That isn't of course a problem, we could just uninstall it, as it will never happen in production, but for my knowledge sake, I tried to implement a simple downgrade.. just drop all tables and create them again.

Called when the database needs to be downgraded. This is strictly similar to onUpgrade(SQLiteDatabase, int, int) method, but is called whenever current version is newer than requested one. However, this method is not abstract, so it is not mandatory for a customer to implement it. If not overridden, default implementation will reject downgrade and throws SQLiteException

This method executes within a transaction. If an exception is thrown, all changes will automatically be rolled back.

Parameters

db

The database.

oldVersion

The old database version.

newVersion

The new database version.

Ok, so I've had to override it to avoid an exception. No problem...

... I thought.

In fact the app crashed when I tried to drop all tables and (re)create them on that method... it seemed strange, as it was a lock on the database problem...