dancingbush
dancingbush

Reputation: 2281

Database error using new version on upgrade

I am adding a column to a DB in the onUpgrade() method which works fine on devices / emulators where the previous DB version exists.

However when installing on devices for first time I get an error starting the column (in on upgrade()) can't be found.

I am assuming this is because the device can't find a previous version so the onUpgrade() is not executed.

Is there a way around this?

Cheers

Here is the code:

@Override 
    public void onCreate(SQLiteDatabase db) {
        // only called once when DB first created, takes DB as arg
        db.execSQL("CREATE TABLE "+ DATABASE_TABLE + " ("+
        KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, " +
        KEY_DIVELOCATION + " TEXT , "+ 
        KEY_DIVESITE + " TEXT , " +
        KEY__DIVENUMBER + " INTEGER DEFAULT 0 , " +
        KEY__DIVEDATE + " TEXT , " +
        KEY_DIVERATING + " FLOAT DEFAULT 0.0 , " +
        KEY_BOTTOMTIME + " INTEGER DEFAULT 0 , " +
        KEY_DIVEBUDDY + " TEXT , " +
        KEY__DIVECENTER + " TEXT , " +
        KEY_ENDBAR + " INTEGER DEFAULT 0 , " +
        KEY_STARTBAR + " INTEGER DEFAULT 0 , " +
        KEY_VIZIBILTY + " INTEGER DEFAULT 0 , " +
        KEY_WATERTEMP + " INTEGER DEFAULT 0, " +
        KEY_COMMENTS + " TEXT , " +
        KEY_CONDITIONS + " TEXT , " +
        KEY_DIVEPICTURE + " TEXT );"
        );
        //use for dtabase querys
        columns = new String[]{KEY_ROWID, KEY_DIVERATING, KEY_BOTTOMTIME, KEY_DIVEBUDDY, 
                KEY__DIVECENTER, KEY_DIVELOCATION,
                KEY__DIVENUMBER, KEY_DIVESITE, KEY_ENDBAR, KEY_STARTBAR, 
                KEY_VIZIBILTY, KEY_WATERTEMP,KEY__DIVEDATE, 
                KEY_COMMENTS, KEY_CONDITIONS, KEY_DIVEPICTURE};



    }//end onCreate DB inner helper class

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // if table exits, drop it (delete) and recreate it to upgrade it
        db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
        onCreate(db);
        //need to call upgrade and add a int column for depth, newVersion is 2
        if (newVersion> oldVersion ){
            db.execSQL("ALTER TABLE "+DATABASE_TABLE+" ADD COLUMN "+KEY_DEPTH+" INTEGER DEFAULT 0");
        }

Upvotes: 0

Views: 96

Answers (1)

Farhan
Farhan

Reputation: 13390

onUpgrade will be only called when a version of database will gets old. i.e you change the version which you passes during database creation.

e.g

super(context, DATABASE_NAME, null,DATABASE_VERSION);

Now if DATABASE_VERSION is changed, only then onUpgrade will gets called...

So i think, you just need to execute your create table commands in onCreate and only use commands of changing tables in onUpgrade. That way you won't have this issue.

Hope it helps

Upvotes: 1

Related Questions