frajerko1 frajerko1 - 2 months ago 9
Java Question

SQLite - Java - onCreate and onUpgrade - Android

Hello i have created my first application which collect some basic information in its local private database using my own class which inherits the

SQLiteOpenHelper


I have noticed that when inheriting i have to implement some of the methods which are :

@Override
public void onCreate(SQLiteDatabase db) {

}

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

}


what i have noticed is : in many tutorials i have seen people were using something like this :

@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE table_name (parameters here...)");
}

@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS table_name");
onCreate(db);
}


Question



i thought the code in the above approach does this: whenever the user restarts the app , it should delete the entire table and recreate it , but it doesnot , so whats the goal of it ? i have just tested it on my phone , and basicaly i close the application and kill the proccess of it , then reopen it and the table is still there with the previous content , its not my goal , sure i want to keep me database between all the sessions but i just dont get this sample code...

in which order are there methods called?

i thought the first is constructor and then onCreate and then onUpgrade but it doesnot delete the table so it means onUpgrade is not getting called?

Answer

public void onUpgrade() is NOT same as onResume(). onUpgrade() will be called only in case where user updates their app with newer version. Restart --> calls either onCreate() or onResume().

For example:

When you created app first time you have table EMPLOYEE with FIRSTNAME and LASTNAME

But in version2 of your app (which would be published at later date) you add new column MIDDLENAME to this table, then onUpgrade() call will be used (for user who are upgrading to new version).

Based on SQLiteOpenHelper documentation:

Called when the database needs to be upgraded. The implementation should use this method to drop tables, add tables, or do anything else it needs to upgrade to the new schema version.