I am working on an update for my current app. My app use SQLite DB and so far I am at version 1. I will need to alter/introduce new tables in my second version. I did my research and I found that to do that the best way is to have switch(case) statements in which I do the updates to db in a fall-through manner.
My question is, how does android know what is the older version in the onUpgrade()?. In fact, when does it get called?.
So for the users who are downloading my updated app for first time, I assume the onUpgrade() will not be called! How would android know when not to call onUpgrade()?
Please clarify this for me. I want to submit my first update and I don’t want to lose my hard-earned users 🙂
When implementing the
SQLiteOpenHelper, you pass a version parameter to the superclass constructor. This should be a static value you can change in future versions of your application (usually you’d want this to be a static final attribute of yourSQLiteOpenHelperimplementation, alongside the database name you pass to the superclass constructor).Then, when you want to update the database, you increment the version parameter that will be used in your
SQLiteOpenHelperimplementation, and perform the SQL modifications you intend to do, programmatically, inside theonUpgrade()method.Say your DB started with table A in version 1, then you added table B in version 2 and table C in version 3, your onUpgrade method would look like:
When the superclass constructor runs, it compares the version of the stored SQLite .db file against the version you passed as a parameter. If they differ,
onUpgrade()gets called.I should check the implementation, but I assume
onUpgrade()is also called afteronCreate()if the database needs to be created, and there’s a way to ensure all of the upgrades are executed (for example, by forcing all version numbers to be positive integers and initializing a newly created database with version 0).