0

it is the first time that I need to change database structure of my app (that has been already published on Google play). This is my database class:

public class Database extends SQLiteOpenHelper {
    private static final String DB_NAME = "db";
    private static final int DB_VERSION = 1;

    public Database(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        String table = "CREATE TABLE users(";
        table += "_id TEXT PRIMARY KEY,";
        table += "name TEXT NOT NULL,";
        table += "surname TEXT NOT NULL,";
        table += "details TEXT);";

        String table2 = "CREATE TABLE favorite(";
        table2 += "id TEXT PRIMARY KEY);";

        String table3 = "CREATE TABLE documents(";
        table3 += "id TEXT PRIMARY KEY,";
        table3 += "text TEXT NOT NULL,";
        table3 += "username TEXT REFERENCES users(_id));";

        String table4 = "CREATE TABLE average(";
        table4 += "user TEXT PRIMARY KEY,";
        table4 += "document INTEGER NOT NULL,";
        table4 += "avg REAL NOT NULL);";

        db.execSQL(table);
        db.execSQL(table2);
        db.execSQL(table3);
        db.execSQL(table4);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    }
}

I have added the following table:

String table5 = "CREATE TABLE categories(";
table5 += "source TEXT PRIMARY KEY,";
table5 += "parent TEXT,";
table5 += "sub TEXT NOT NULL);";

and then add this:

db.execSQL(table5);

So now, what have i to add in onUpgrade method to make users have the updated database on their device? Sorry if it could be a dumb question, but I'm not sure to be able to do that and I want to feel safe about making users to get the right structure in the new version of the app.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
smartmouse
  • 13,912
  • 34
  • 100
  • 166

1 Answers1

0

onUpgrade() is called when the database exits and the version number is lower than requested in the constructor. The method will update the table schema to the requested version.

You'll find more information here: "When is SQLiteOpenHelper onCreate() / onUpgrade() run?"

Community
  • 1
  • 1
timbillstrom
  • 1,176
  • 16
  • 33