Delete database when on app update - android

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);
}

Related

When I clear data from my Android device, it wipes out the tables that were created in onUpgrade method of my DB helper

When using SQlite database in my android app, I have two tables being created in onUpgrade method. On my test device, if I go to settings > apps > myApp > storage and press "Clear data" button, the next time I want to test the app, it crashes and complains that the two tables does not exist. I am fairly new to SQlite world, so any instruction would be appreciated.
Here is part of my DBHelper class:
#Override
public void onCreate(SQLiteDatabase sqLiteDatabase) {
sqLiteDatabase.execSQL(SQL_CREATE_MAPS_TABLE);
}
#Override
public void onUpgrade(SQLiteDatabase sqLiteDatabase, int oldVersion, int newVersion) {
if (oldVersion < 2) {
sqLiteDatabase.execSQL(SQL_CREATE_TRACK_RECORD_TABLE);
sqLiteDatabase.execSQL(SQL_CREATE_TRACK_POINT_TABLE);
}
}
If you delete the App's data, then the onUpgrade step will not run because the onCreate method runs, which will set the version to the coded version.
If you need to delete all existing data and change the schema then you code to create the new schenma (tables etc) should be in the onCreate method. The onUpgrade method is intended for introducing changes to an existing database.
Thank you very much Mike! I just don't understand the difference.
This is what happens when the database (a file) is opened (i.e. an attempt is made to access the database via an instance of the Database Helper) via a Database Helper (a class that extends SQLiteOpenHelper).
A check is made to see if the the database file (ie the database's name is the file name) exists at the given location (typically data/data/the_package_name/databases/the_database_name).
the_package_name and the_database_name will differe from app to app.
If the database file does not exist then create the file setting the user version (version) in the file's header to the version passed via the Database Helper (other things are done such as creating the sqlite_master table (done by the SQLite API) and adding the android_metadata table that store the locale). The file is now open so onCreate is called and a jump is made to step 4.
If the file does exist then get the user version stored in the file's header if it is not the same as the version number passed via the Database Helper then
if the version passed via the Database Helper is greater then the version extracted from the file's header then call onUpgrade passing the version as per the file's header and the version passed via the Database Helper and a jump is made to step 4.
if the version passsed via the Database Helper is less than the version extracted from the file's header then call onDowngrade passing the version as per the file's header and the version passed via the Database Helper and a jump is made to step 4.
The database has now been opened so return to the doing the user's request.
As such deleting the App's data takes the path 1 (check if db exists), 2 (create db, setting version and call onCreate) and then 4 (hand control back).

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://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.

Dropping SQLite database on upgrading application

I implemented an Android application which use Sqlite database.
When I release a new version of my application (not in playStore), I upload it on my server, so, if the old application is running, calling web service, can understand that new version is available. So, new version is downloaded and installed.
When the application is overinstalled, the database is not dropped, so if I need to do any changes of my database I need to use the method:
public void onUpgrade(SQLiteDatabase _db, int oldVersion, int newVersion)
This is fine, unless I need to do many changes in my database. In this case, the code becomes unreadable. So I would to delete the database and create a new one.
How can I perform this task?
EDIT: What about using context.deleteDatabase(DATABASE_NAME); ?
For throw-away databases (where the data is e.g. a cached copy of data available in the cloud) I usually make onUpgrade() just call onCreate() and make onCreate() execute DROP TABLE IF EXISTS <tablename> before creating the tables.
For example:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
onCreate(db);
}
#Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS foo");
db.execSQL("CREATE TABLE foo(bar INTEGER, baz TEXT");
}
you can think about this one
keep a trace of your upgrade using a flag in shared preference. when you are downloading new version then set the flag to true. on every launch check the flag. if the flag is true then recreate the database and set the flag false.
I havn't tried similar things but I think it should work in your case.
and to delete database context.deleteDatabase(DATABASE_NAME);
If you just want to re-create your whole database, just drop every table in the old one.

Perform specific operation at the time of installing apk?

I have updated the application's database. But users who have updated the application from market will see a crash everytime app is started because new database structure is not compatible with old database. Its not good to ask them to uninstall and install the app, I need to perform an operation just for single time at the time of installation i.e. clear the old database and create new one. This should not be called everytime the app starts, only at the time of installation..or when the app starts for the first time.
I think I have clearly defined my situation, now where do I go from here? Should I bug users to uninstall and install app or its possible to do what I have asked?
Just change the version of your database and by overriding onUpgrade on your DatabaseHelper class.
private static final int DATABASE_VERSION = 2;
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion
+ ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CREATION);
onCreate(db);
}
Why don't you implement the onUpgrade() method of SQLiteOpenHelper?
This class provides useful onCreate() and onUpgrade() methods.
See here : Is the onUpgrade method ever called?
Or here : How to update table schema after an app upgrade on Android?
First of all it is really a bad idea to clear the old database and create a new one (Users will be really pissed seeing there data lost).
You should always try to upgrade the previous data with new columns and stuff. Instead of clearing the whole data, you should always try to alter the structure of tables without clearing the data.
One more thing is that you can upgrade to new database in onUpgrade() method of the DBHelper class.

Does an Android database get completely removed and recreated then updating an app?

I have an app that uses a database. At startup I check to see if my tables are missing and if so I create them. Works great.
I've noticed that if I "adb uninstall" then the next time I run my app the tables are created again (this is what I need), but what about when updating through the marketplace?
I'm in the process of releasing an update, and I've made major changes to the tables. I'd like it if the tables were completely wiped and re-created, in fact my app needs this to happen. If someone updates and has the old tables then there will be a force close.
Does anyone know the specifics of this scenario?
My tables are only for lookup, I store no user data so I dont really care about losing data on the updates.
Of course I know an option is to use some type of "version" table and check to see if I need to manually drop and create, but I was wondering if that was even needed.
Thanks.
On an update the tables are left alone. I'm going to assume you have implemented a subclass of SQLiteOpenHelper to explain this. The way Android is able to handle version changes is through the use of onUpgrade in the SQLiteOpenHelper class. This method is called from SQLiteOpenHelpers constructor if the DB version is older than the version the app expects. From inside onUpgrade is where you are going to drop your old tables and create the new ones.
onUpgrade (SQLiteDatabase db, int oldVersion, int newVersion){
Log.w(TAG, "Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
//we can change this to perform different behaviors
db.execSQL("DROP TABLE IF EXISTS "+MYDB.TABLE_NAME);
onCreate(db);
}
It is important to note the way Android tells if you are using a new DB version.
DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
That field DATABASE_VERSION is used, so you should use a final static int member as part of your DB implementation.
Hope that helps, leave me a comment if you have questions.

Categories

Resources