7

I'm attempting to update my database table with the following code:

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

        String query = "ALTER TABLE names ADD COLUMN hidden integer default 0";
        dbHelper.getWritableDatabase().rawQuery(query, null);

    }

However, when I start the application and it tries to upgrade the database I get the following exception:

    ...Caused by: java.lang.IllegalStateException: getWritableDatabase called recursively

Does anyone know how I can get around this issue and what exactly is causing it?

Thanks

Nick
  • 6,375
  • 5
  • 36
  • 53
  • this can't be the only place this part of the code gets called is it? – JoxTraex Feb 05 '12 at 20:54
  • Yes, this is the only place the code is called. I put a log statement in the function as well and it is only called once. – Nick Feb 05 '12 at 21:00
  • Then do a check if old version is < new version.this will make it exclusive, although I am not sure why it is being called multiple times. – JoxTraex Feb 05 '12 at 21:01
  • onUpgrade() should only be called when the old version < new version anyways, right? Also, since the log statement is only printed once, the function is only being called once. – Nick Feb 05 '12 at 21:11

1 Answers1

24

Don't call getWritableDatabase(). Use the one passed in:

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

    String query = "ALTER TABLE names ADD COLUMN hidden integer default 0";
    db.rawQuery(query, null);

}

Why? When you call getWritableDatabase() the OpenHelper is detecting that the database needs to be updated, hence it starts up the recursion warning you're seeing. In other words, you're in onUpgrade(). You call getWritableDatabase(), which sees an upgrade is needed. Were it not for the check, you'd be right back into onUpgrade(), ad infinitum.

Brian Dupuis
  • 8,136
  • 3
  • 25
  • 29
  • So... what if you are migrating data that requires the use of utility classes instead of simple db.rawQuery or db.execSQL statements? I need to migrate/manipulate data to complete an upgrade. – Shellum Mar 02 '12 at 21:55