mardi 2 juin 2015

Android SQLiteDatabase update schema without loosing data

I'm using SQLiteDatabase in my app. My SQLiteOpenHelper.onUpgrade(..) method looks like this:

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

    //Save current data
    ArrayList<Course> tempCourses = getAllCourses();

    //Drop tables
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_COURSES);
    db.execSQL("DROP TABLE IF EXISTS " + TABLE_ASSIGNMENTS);

    //create new tables
    onCreate(db);

    //Add temp data back to the database
    for (Course course : tempCourses) {
        addCourse(course);
    }
}

I want to keep the old userdata when upgrading the database schema. However I get the following error when i increase the database version and start my app:

...
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.tak3r07.unihelper/com.tak3r07.CourseStatistics.MainActivity}: java.lang.IllegalStateException: getDatabase called recursively
...

This is because getAllCourses() will open the database again to get the data which calls the onUpgrade method (obvious loop). But how should i store my userdata then?

Regards, Tak3r07

Aucun commentaire:

Enregistrer un commentaire