lundi 9 mars 2015

Updating preloaded sqlite database without losing user data in android

I have done a few searches and read a number of posts but I am still not successful trying to update a database without losing the data that is already saved.


I created the DB using this tutorial: http://ift.tt/19PBhQ1


In the new database I want to migrate data from a main table to a new table that will store the user's favourites. Currently, they are stored in the main table. In the onupgrade function I tried renaming the table and inserting the record into the new table. That didn't work. I also tried saving the data to a cursor and then populating the new table but that didn't work. For these methods, I got errors saying that the new/old table cannot be found.


Below is the onUpgrade() function.



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

if (newVersion > oldVersion) {
db.execSQL("ALTER TABLE books rename to old_books");


try {
copyDataBase();

} catch (IOException e) {
throw new Error("Error copying database");

}


db.execSQL("INSERT into favourites (_id, type, title, notes,rating) SELECT _id ,type, title, notes, rating FROM old_books where rating > 0;");
db.execSQL("DROP TABLE IF EXISTS old_books;");
}
}


Is there a better way to update the database without losing data using the implementation from the tutorial? All I need to do is copy the favourites from the "books" table and load them to the "favourites" table when users update the app.


Aucun commentaire:

Enregistrer un commentaire