Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
338 views
in Technique[技术] by (71.8m points)

android - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...