Eric Berman
Eric Berman

Reputation: 161

SQLiteOpenHelper onUpgrade getting called multiple times

I have a read-only database in my android app that I update periodically. The app always carries with it the up-to-date version of the database in its assets.

I increment the version number that I pass into the constructor for my SQLiteOpenHelper subclass, bumping it (in this case) to version 4.

I have the following code:

public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    // copy from assets to local storage; version really doesn't matter;
    // DB will be opened from the target location. 
    copyDataBase();
}

This gets called when I make a call to get a readable database:

SQLiteDatabase db = myDBHelper.getReadableDatabase();
// Here db.getVersion() correctly returns "4", the newVersion.
// db is also usable and has the correct data.

But each time I call getReadableDatabase onUpgrade gets called from oldVersion=3 to newVersion=4.

Any ideas why the version isn't sticking?

Upvotes: 2

Views: 1575

Answers (2)

Mo1989
Mo1989

Reputation: 2494

This is just a guess. I was having the same problem so I came across this post. I later realised that i was using sqLiteDatabase.beginTransaction(); and sqLiteDatabase.endTransaction(); but was not calling sqLiteDatabase.setTransactionSuccessful(); before I ended the transaction. I put that in and it fixed it. Hope this helps though I know its pretty late.

Upvotes: 1

Fraggle
Fraggle

Reputation: 8727

Well a couple of things.

The "copyDataBase()" call is a bit suspicious as it could be copying some saved copy of your db which has the old version code in it. db.getVersion() might be using whatever was passed to the constructor of your helper class and not actually reading it from anywhere. So I would double check that or post it.

Also make sure you are indeed calling the super constructor from your sub class:

   DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
        Log.d("DatabaseHelper", "constructor. Version="+DATABASE_VERSION);
    }

And make sure the log output shows "4" and not 3 in your case.

Upvotes: 1

Related Questions