why we need to onUpgrade(); method in SQLiteOpenHelper class

Qadir Hussain picture Qadir Hussain · Mar 27, 2013 · Viewed 13.3k times · Source

I m following this tutorial.http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/

can any body please make me clear this chunk of code.

 // Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
    String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
            + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
            + KEY_PH_NO + " TEXT" + ")";
    db.execSQL(CREATE_CONTACTS_TABLE);
}

// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // Drop older table if existed
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);

    // Create tables again
    onCreate(db);
}

Questions

What is the purpose of onUpgrade(); method?

When it is Called? as docs says this is Called when the database needs to be upgraded what does it means by upgrading the database?

Important

why we drop the table in this method and recreate?

Thanks in advance.

Answer

Deva picture Deva · Mar 27, 2013

onUpgrade is basically for handling new db changes(could be new columns addition,table addition) for any new version of your app.

Droping the table is not always necessary in onUpgrade it all depends on what your use case is. If the requirment is to not to persists the data from your older version of app then drop should help,but if its like changing schema then it should only have alter scripts.