Updating preloaded sqlite database without losing user data in android - 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://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/
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.

onUpgrade is called while the database is open and a transaction is active.
You cannot overwrite the database file at this time (and this would lose all the data in the old file).
Just remove the copyDataBase() call.

if you are using SQLite browser to get preloaded database so you can update the database file then change it's version not create a new database file and keep the data ! Source tutorial .... in my opinion this tutorial is better and more detailed than the one you refereed.

Related

Delete database when on app update

I have preloaded sqlite database located in assets, which is copied to default database location after app first installation. I'd like to do this procedure on each app update.
I don't need to keep any user data from existing database.
How to delete old database file, when app is being updated?
These are actually two questions:
How do I do something on app update
You could save a variable with the last version code in a Shared Preferences. After each start of the application you check your current code with the saved code. If they don't match, it was an update and you execute some code.
How do I delete a database
If the database is closed, you can simply delete the file. Use Context.getDatabasePath(String) to find the location of the file, and File.delete() for deleting it. Make sure no process is accessing the database file. If so, you might need to use the File.deleteOnExit() and force a restart of the application.
Use onUpgrade() method of SQLiteOpenHelper class.
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Delete old table
db.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
// Re-create table
onCreate(db);
}

About the update of SQLite in Android

About the update of SQLite in Android.When you change the structure of the datebase,how can we update the datebase without delete the data?
You should override the onUpgrade Method in the SQLiteOpenHelper. You should code something like this.
public void onUpgrade (SQLiteDatabase db,int oldVersion,int newVersion){
String update = ALTER TABLE <table_name> ADD COLUMN <column_name> <column_type>;
db.execSQL(update);
}
Dropping a table, adding a row, inserting/updating/deleting data should be done here.
Alter Table gives you very limited options in performing an update to the database tables. If you want to copy your data into a completely new structure, you should think about creating temporary tables where you can copy data, create the new schema and then copy your data from the temporary tables to the new table, in this upgrade method.
Make sure you have your DB Version numbers correctly updated while creating the DBHelper.

The best way to overwrite an SQLite database table in Android?

When there is new data available to my Android application I need to completely remove all current entries in one of the SQLite database tables and replace them all with the new data. What is the best way to do this?
Would it be best to run
DELETE * FROM my_table
or
run a delete query for every row in the database
or run
database.execSQL(DATABASE_DROP_MY_TABLE);
database.execSQL(DATABASE_CREATE_MY_TABLE);
Where DATABASE_DROP_MY_TABLE is SQL to drop the table and DATABASE_CREATE_MY_TABLE is
SQL to create the table again with no entries.
And then following one of these, insert the new data.
Of course there are probably other ways to do this that I have not thought of.
Assuming you're using SQLiteOpenHelper, you can just close db, delete the whole file and recreate the db:
class MyDatabase extends SQLiteOpenHelper {
public static final String DB_NAME = "wat";
public MyDatabase(Context context) {
super(context, DB_NAME, null, CURRENT_VERSION);
}
}
dbHelper.close(); // dbHelper is your MyDatabase instance
context.deleteDatabase(DB_NAME);
SQLiteDatabase db = dbHelper.getWritableDatabase() // will create empty db
Nice thing about this solution is that you won't have to update table resetting code when you add new tables to your schema. It also correctly recreates indexes you might have added.
I wouldn't complicate things, and simply drop the table with DROP TABLE statement. As the doc say:
The SQLite DROP TABLE statement is used to remove a table definition and all associated data, indexes, triggers, constraints and permission specifications for that table.
You would have clean plate, then create the table again and add your new data.

Upgrading Sqlite database in android?

I have an android application which is using Sqlite as database.It has following tables:
Hotels
Locations
Favorites
I am keeping my raw database file in assests folder and when user installs my app i just copies this database to /data/data/package_name/databases directory.Initially Favorites table is empty and it gets populated after user start liking hotels.My problem is that I want to launch my updated version of app with some bug fixes and some new hotels added to the database, so I need to update database of existing users with new hotels and locations without affecting the favorites table.Now if I keep my old approach and update the Database Version Number then application will remove the old database and use the new database but all data in favorites table will be lost.I don't want it to happen.Now problem is how do I update Hotels and Locations table without loosing data in Favorites table.
I know this question was asked long ago, but I had a similar issue and wanted to share my solution, seems to do the trick for me. I'm a novice so feel free to give input-
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
//code to keep table data
List<obj> objList = new ArrayList<obj>();
String selectQuery = "SELECT score,list_name,quiz_length FROM obj_table";
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
obj o = new obj();
o.final_score = cursor.getInt(0);
o.quiz_name = cursor.getString(1);
o.quiz_length = cursor.getInt(2);
objList.add(o);
} while (cursor.moveToNext());
}
//done storing data, now upgrade DB from asset file
try {
//my db file is upgraded here
copyDataBase();
} catch (IOException e) {
}
//now insert our saved table data
for (Score obj_rec: objList){
ContentValues values = new ContentValues();
values.put("score", obj_rec.final_score);
values.put("list_name", obj_rec.quiz_name);
values.put("quiz_length", obj_rec.quiz_length);
db.insert("obj_table", null, values);
}
}
Before updating write the contents of you previous table to a file and save it on the sdcard.
Then you may update your database with new version.
And after doing that copy back the data from the backup file(from sdcard) to the updated database. After the successful copying of the backup, delete the file from the sdcard.
Usualy upgrade a database has to be done with SQLiteOpenHelper class. I would advise You to do some tests at Your own device before publish it. You have to increment Your Database Version and call "ALTER TABLE" method from sqlite. This has been discussed in many threads here, the clearest one I think is this one:
Difficulty in upgrading SQlite table
and here is even a article with some solution:
http://joshhendo.blogspot.de/2012/03/android-sqlite-database-upgrade.html
However, a safe way would be to save the old database in a tempfolder, that the user can get back the old one if anything is running into chaos.

How to update an SQLite Database and NOT lose all existing data?

I'm adding a table to my app's SQLite DB. All my syntax there is fine, not the issue. But I'm having some trouble getting the new table to be created properly. I added the new table....
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(DATABASE_CREATE);
db.execSQL(CREATE_REQUESTS);
db.execSQL(CREATE_OVERRIDE);
}
My on create method. I have 3 tables. When I updated the version number, I got an error saying "table requests (referring to CREATE_REQUESTS) has already been created." A look at my onUpgrade method...
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS contacts");
onCreate(db);
}
Led me to understand that the line db.execSQL("DROP TABLE IF EXISTS contacts"), which refers to my DATABASE_CREATE table in the onCreate method, is used to drop the old table, then the next line, onCreate(db); recreates it. I did not add requests into that execSQL line, which is what caused the error. Here is the issue: I would rather not lose the data in the two tables I already have. Is there a way to add a table like I am trying to do, and not lose all the old data? Thanks.
You can do anything you want in onUpgrade. You can use ALTER to add new columns to your table.
Worst case, if your schema is completely and entirely different, you'll have to create the new table, populate it using data from the old table, and then delete the old table.
In any case, onUpgrade was designed to allow for a smooth upgrade without any loss of data. It's just up to you to implement it properly.
if DB version : 6
Ex : There is a table with 5 columns
When you upgrade to : 7 ( I am adding 1 new column in the 3 tables)
1. We need to add the columns when creating a table
2. onUpgrade method:
if (oldVersion < 7)
{
db.execSQL(DATABASE_ALTER_ADD_PAPER_PAID);
db.execSQL(DATABASE_ALTER_LAST_UPLOADED);
db.execSQL(DATABASE_ALTER_PAPER_LABEL);
}
Where : "DATABASE_ALTER_ADD_PAPER_PAID" is query.
EX: public static final String DATABASE_ALTER_ADD_PAPER_PAID = "ALTER TABLE "
+ TableConstants.MY_PAPERS_TABLE + " ADD COLUMN " + COLUMN_PAPER_PAID + " TEXT;";
After above two operation it will works fine for the fresh install user and app upgrade user

Categories

Resources