Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 870
Qadir Hussain Avatar asked Mar 27 '13 19:03

Qadir Hussain


People also ask

What is onUpgrade?

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.

What is onUpgrade in SQLite?

onUpgrade method is called when the database version increases, not when the number of column is changed.

Why do we use class SQLiteOpenHelper?

SQLiteOpenHelper Class: We can use this class for creating a database and also we can use it for version management. This class provides the onCreate() and onUpgrade() methods for performing any database operation. SQLiteOpenHelper class has two constructors.


1 Answers

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.

like image 165
Deva Avatar answered Nov 15 '22 22:11

Deva