简体   繁体   中英

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?

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.

onCreate() is called when the database is to be created.

onUpgrade() is called when you increase the database version number. In this case, you'll delete everything in the table and start over.

You'll have to drop the tables manually every time the app resumes if you want to clear the database like this. Then call onCreate() again to rebuild it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM