Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORMLite update of the database

I'm actually developing an app which is using ORMLite library (which is wonderful btw) but I'm a beginner using it.

I have a question about the update of the database inside the device.

Let's say that someone download my app on the Google Play. Few months later I will certainly populate some tables with new entries.

When this person is doing an update of the app, how can I just update the database with my new entries and keep the old ones inside it.

To be more clear, imagine that the user answered questions in my app. When I will introduce new questions, how can I insert them in the db when he updates my app and keep the questions that have already been answered ?

like image 690
Alexis C. Avatar asked Dec 08 '12 21:12

Alexis C.


1 Answers

When this person is doing an update of the app, how can I just update the database with my new entries and keep the old ones inside it.

The idea is to use the version number that is passed to the onUpgrade(...) method. With ORMLite, the OrmLiteSqliteOpenHelper.onUpgrade(...) method takes an oldVersion and newVersion number. You then can write conversion code into your application that is able to convert the data from the old format and update the schema.

For more information, see the ORMLite docs on upgrading your schema.

To quote, you could do something like the following:

if (oldVersion < 2) {
  // we added the age column in version 2
  dao.executeRaw("ALTER TABLE `account` ADD COLUMN age INTEGER;");
}
if (oldVersion < 3) {
  // we added the weight column in version 3
  dao.executeRaw("ALTER TABLE `account` ADD COLUMN weight INTEGER;");
}

If you have existing data that you need to convert then you should do the conversions in SQL if possible.

Another alternative would be to have an Account entity and an OldAccount entity that point to the same table-name. Then you can read in OldAccount entities using the oldAccountDao, convert them to Account entities, and then update them using the accountDao back to the same table. You need to be careful about object caches here.

like image 175
Gray Avatar answered Sep 21 '22 21:09

Gray