Update pre-loaded database with existing data - android

I have an app which is online on play store. It comes with a preloaded database, which is bundled inside assets folder and when user initially launches the app, db is copied to preferred folder.
There is a table of favourites , in which user stores there bookmarked/favourite records.
I have new data and few other modifications which I have made with bundled database, and will be uploading new APK to play store.
My concern is that, users who are currently using my app, they will get update notification and once they update, their app will use new bundled database, and they will lose their records stored in favourites.
I did some google search on it, and SQLiteHelper onUpgrade() works when we are creating database on runtime, but in my case its pre-loaded bundled database.
How can I backup the favourites data before update and then load it back in new db file.
Thanks

In the newer versions, you should preserve the table data that you want to keep. To do this, you could:
Make a copy of the old database file into a backup.
Extract the newer database file to the working directory
Open two SQLiteDatabase objects, one for each database file.
Copy all data from the tables you want to preserve.
Delete the backup of the old file if everything was successful.
For step 4 you shouldn't even need to code specifically, it can be done for every table, for example more or less like this (warning, this code is untested):
static void copyTable(SQLiteDatabase source, SQLiteDatabase destination, String tableName)
{
Cursor c = source.query(tableName, null, null, null, null, null, null);
destination.beginTransaction();
try
{
String[] columns = c.getColumnNames();
ContentValues insertValues = new ContentValues();
while (c.moveToNext())
{
insertValues.clear();
for (int i = 0; i < columns.length; i++)
insertValues.put(columns[i], c.getString(i));
destination.insert(tableName, null, insertValues);
}
destination.setTransactionSuccessful();
}
finally
{
destination.endTransaction();
}
c.close();
}

Related

Empty sqlite database when app send on another device

I am developing Android app and I have SQLite database in it. I have inserted records in database. Now when I am sending my app into another device there is empty database!. Please help me
public void createPrincipal(CollegePrincipal principal){
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(PRINCI_NAME, principal.getName());
values.put(PRINCI_QUALI, principal.getQalification());
values.put(PRINCI_INTRO, principal.getIntro());
// insert row
long princi_id = db.insert(TABLE_PRINCI, null, values);
Log.e("princi id", String.valueOf(princi_id));
}
when ever you create data base it will in the local store of your device , And when you transfer app it wont care you local data you need store those data variables in you code to get in the another device.

Is there a memory cache for SQLite in Android and how to release or clear it?

Firstly, I create a database called "mydb" in my Android app:
DBHelper dbHelper = new DBHelper(context, "mydb", null, 1);//DBHelper is my custom class
And write some data into it's table:
SQLiteDatabase db = dbHelper.getReadableDatabase();
db.execSQL("insert into mytable(name, text) values ('allen','hello')");
Here, everything is ok. But then, i delete this database manually not by programming, with a software "R.E. explore" (Certainly on a rooted device).
Then, in my code, i read this table of the database. What is astonishing is that i still could get the data I stored.
Cursor cursor = db.query("mytable", new String[]{"name","text"}, null, null, null, null, null);
Why?
Quoting from the Android Developers reference website:
Once opened successfully, the database is cached, so you can call
this method every time you need to write to the database. (Make sure
to call close() when you no longer need the database.)
This is from the description of the getWritableDatabase() method, however both getReadableDatabase() and getWritableDatabase() return basically the same object for reading the database.
Please note that you should use getWritableDatabase() if you want to persist the changes you make to the database on the device's internal memory. Otherwise they will be valid only for the duration of the application's runtime and will be discarded once the app is closed. If you wish to delete the database completely, you should call the SQLiteDatabase's close() method in order to invalidate the cache.
use SQLiteDatabase.deleteDatabase(File file) API to delete the database
Deletes a database including its journal file and other auxiliary files that may have been created by the database engine.
Make sure you have closed all the connections that are open.
In case you are not able to do that,
just cal the deleteDatabase followed by kill process.. - not recommended
You need to delete the app from your phone then install again

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 store bulk questions in android sqlite db?

I am working on quiz application. In my project I need to store huge number of questions to display on the screen. How can I do that? I have downloaded the sqlite browser and when I tried to import .sql file it is displaying error. Also I have kept the .sql file in assets folder in eclipse.
How to store those questions into my sqlite db?
The thing is that even if you port the .sql file to the assets folder in eclipse its not going to work like that when you are going to use it in a real android mobile rather that an emulator by using the final .apk file.
One method what i did was to enter all the entries using a method. In order not to do this at each load, i check if the number of entries is the same else i drop the table and then enter it new once again. Thats the option that i know of. Maybe there are better options. But this works for sure.
public long createValue(int semester, String subname, int credits)
{
ContentValues initialValues = new ContentValues();
initialValues.put(KEY_SEMESTER, semester);
initialValues.put(KEY_SUBNAME, subname);
initialValues.put(KEY_CREDITS, credits);
return mDb.insert(DATABASE_TABLE, null, initialValues);
}
Create a method like the above to enter the values and then call this method with the values to enter. So you can just have n number of calls to this method with the values to enter.
mDb is a SQliteDatabase object
Maybe this will help you out.

Dynamic Database Backup for certain tables

I need to backup just some of the tables in my main database. The other tables are reference and are static so do not need to be backed up.
I have created a new blank DB that is on the SDCARD. Can I access the DB directly on the SDCARD or do I need to copy it when its finished backup?
The real question is can I iterate through the fields in each record in a loop or something so I dont have to have hundreds of line of code, one for each field.
In VB .NET I would do something like
For X = 0 to RS.Fields.Count
NewRS.Fields(x).value = Rs.Fields(x).value
etc... How wound I do that in android?
I wrote a class to handle this. Yes my DB is at least 95% reference...
Here is the guts of the code:
Cursor c = DbBak.rawQuery(Sql, null);
String Cn[] = c.getColumnNames();
if (c != null ) {
if (c.moveToFirst()) {
do {
for ( x=0; x< c.getColumnCount(); x++)
{
newRow.put(Cn[x].toString(), c.getString(x));
}
Db.insert(TableName, null, newRow);
}while (c.moveToNext());
Unless your reference tables make up 95% of your database size, I'd just copy the database file using standard Java file I/O, while the database is closed. That will be substantially faster than trying to schlep the data over cell-at-a-time.

Categories

Resources