Search code examples
androidsqliteopenhelper

What the version mean in the abstract class SQLiteOpenHelper of Android


There is a parameter in the constructor of the virtual class SQLiteOpenHelper called version(like below shows)

public SQLiteOpenHelper(Context context, String name, CursorFactory factory, int version) {
        this(context, name, factory, version, null);
    }

What i want to know is what's the meaning of the version?Can anyone help me on this?


Solution

  • Its the Database version you ship with the Application. So in the future if you want to add a table or delete a column or anything which differs from the previous Database version. This version Number will come handy.

    This is an example of how I manuplated DB on upgrades of my application: The method is defined by the framework, onUpgrade()

    Class Level Variable:

    private static final int DATABASE_VERSION = 4;
    

    Check against the current version:

            @Override
            public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
                if (oldVersion < 2) {
                    db.execSQL(DATABASE_CREATEX);
                }
                if (oldVersion < 3) {
                    db.execSQL(DATABASE_CREATEC);
                }
                if (oldVersion < 4) {
                    final String ALTER_TBL = "ALTER TABLE " + DATABASE_TABLE1
                            + " ADD COLUMN Vcost text;";
                    final String ALTER_TBL1 = "ALTER TABLE " + DATABASE_TABLE1
                            + " ADD COLUMN Vmedicine text;";
                    db.execSQL(ALTER_TBL);
                    db.execSQL(ALTER_TBL1);
    
                    final String ALTER_TBL2 = "ALTER TABLE " + DATABASE_TABLE2
                            + " ADD COLUMN Dcost text;";
                    final String ALTER_TBL3 = "ALTER TABLE " + DATABASE_TABLE2
                            + " ADD COLUMN Dmedicine text;";
                    db.execSQL(ALTER_TBL2);
                    db.execSQL(ALTER_TBL3);
    
                }
    
            }
    

    So it checks based on all versions of the DB and it acts according to the current version which is present on the device.