Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 253
sai android Avatar asked Jun 01 '18 09:06

sai android


People also ask

How do I add a new column in SQLite?

The syntax to ADD A COLUMN in a table in SQLite (using the ALTER TABLE statement) is: ALTER TABLE table_name ADD new_column_name column_definition; table_name. The name of the table to modify.

How do I add multiple columns in SQLite?

How do I add multiple columns in SQLite? SQLite does not support adding multiple columns to a table using a single statement. To add multiple columns to a table, you must execute multiple ALTER TABLE ADD COLUMN statements.

Is SQLite deprecated in Android?

In which case, does that mean that SQLLite is deprecated in Android? No.


2 Answers

(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.

like image 88
Harsh4789 Avatar answered Nov 14 '22 21:11

Harsh4789


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);        
}     
like image 28
Mohsin mithawala Avatar answered Nov 14 '22 22:11

Mohsin mithawala