- Android Development: Database Upgrades
- Android Development: Missing API
- (Not) Integrating Application with Intents
- Android Activity Lifecycle
- URI Matching in Android’s IntentFilters
- Android Intent Sender Verification
- Android Jittery Scrolling Gallery
- Encryption on Android & BouncyCastle
- Android Permission Handling
- ContentProvider Curses Cursor
- ContentProvider Wasted Potential
Turns out that you can. Or rather, you can reset your database’s schema manually, which lets you re-use one schema version over and over during development, and ship with schema version increments of exactly one.
The first and obvious choice for that is a function in the SQLiteDatabase class that’s called setVersion()1. You could call that… well, when exactly?
One obvious candiate to use this in is the onOpen() function in SQLiteOpenHelper. The thing is, that function is called after onUpgrade() has completed, and is less than ideal.
Granted you could let onUpgrade() finish, then crank down the stored schema version so the next time you open the database the upgrade is attempted again.
Maybe it’s just me, but I find such code slightly distasteful. The biggest issue with it I have is that I’m forgetful… I might accidentally ship that code, and my app might re-try the database upgrade over and over again.
I much prefer modifying the database file itself whenever I want to test the upgrade code. That’s also possible, and here’s how you do it.
- First, restart adb as root:
$ adb root - Then, log in to your device:
$ adb shell # - Next, open the database file. You know the file name because you passed it to
SQLiteOpenHelper‘s constructor. The path to that file, on the other hand, includes your app’s package name. We’ll usede.unwesen.examplefor the package name, andmy.dbfor the database file name here:
# sqlite3 /datat/data/de.unwesen.example/databases/my.db SQLite version 3.5.9 Enter ".help" for instructions sqlite>
- Now, all you need to do is set the schema version you want. Let's use
5here, because I haven't mentioned that before:sqlite> PRAGMA user_version = 5; sqlite>
And that's it! The next time your app opens the database, any upgrades from version 5 to the version you're opening the database with will be performed. You can force the app to open the database by reinstalling it2.
All of this may not sound exactly like rocket science, but you might be surprised by the suggestions I've found on the intarwebs. I'll let you search for that yourself, if you're that curious.
- There’s a corresponding getVersion() as well. [↩]
- Don't uninstall and install it, or your data will be lost. Use the reinstall target from the build system. [↩]
![Reblog this post [with Zemanta]](http://img.zemanta.com/reblog_c.png?x-id=b09b62b4-aa9a-427b-9ff9-d021a90b11e4)


