How can I add new columns to a SQLite database after the Android app is released?

对着背影说爱祢 提交于 2019-12-19 04:12:43

问题


I want to add new columns to a SQLite database, but I already released my app on the Play Store so, if I edit it, users need to uninstall and reinstall the app, but I don't want that. Please, help, I am new to Android.


回答1:


(1) Increment (or simply change) your database version
(2) It would lead to onUpgrade() method call
(3) Execute your query(for adding a new column) in the onUpgrade() method.

The Right Way of doing is mentioned here in this blog.

Sometimes user may update the version 1.5 from the version 1.1.In other words, They may skip the other versions between the 1.1 to 1.5. You might changed database couple of time between 1.1 to 1.5. So in order to give the user a benefit of all the database changes, you need to take of onUpgrade() method as below.

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   if (oldVersion < 2) {
        db.execSQL(DATABASE_ALTER_TEAM_1);
   }
   if (oldVersion < 3) {
        db.execSQL(DATABASE_ALTER_TEAM_2);
   }
 }

Hope it helps.




回答2:


You need to changes in following method of Database Class

@Override 
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    String sql = "ALTER TABLE " + TABLE_SECRET + " ADD COLUMN " +
     "name_of_column_to_be_added" + " INTEGER"; 
    db.execSQL(sql);        
}     


来源:https://stackoverflow.com/questions/50640535/how-can-i-add-new-columns-to-a-sqlite-database-after-the-android-app-is-released

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!