i have a android app of version 4.20 inside 10M sqlitedb, now i have a app of version 4.21 inside 100M sqlitedb,i want upgrade 4.20 to 4.21, when it upgrade have completed, i find the sqlite size still keep 10M in 4.21 app.
so the question is how to override sqlitedb when upgrade app 4.20 -> 4.21 。
My business is: app will have a lot of data synchronization. In order to optimize, every app will fill in initialization data into SQLite when it is published. Therefore, after each app have upgraded, I hope to completely overwrite SQLite。
any help is very apprecated.
You can upgrade your database version and in the onUpgrade() method of your SQLiteOpenHelper drop all tables and call onCreate() method for recreat database.
public class MyOpenHelper extends SQLiteOpenHelper {
...
private void resetDB(SQLiteDatabase db) {
// Drop all tables
db.execSQL("DROP TABLE IF EXISTS table_name");
// TODO duplicate above line for other tables
// Crate tables again
onCreate(db);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
resetDB(db);
}
#Override
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
super.onDowngrade(db, oldVersion, newVersion);
resetDB(db);
}
}
The Problem is the onUpgrade function is not being called because when you load a database from assets the the default version is 0.
And when you call the db.getReadableDatabase() or db.getWriteableDatabase which is supposed to call the onUpgrade method, it fails because the version number 0 which is supposed to be a fresh database.
If you see the SqliteOpenHelper source code
db.beginTransaction();
try {
//Skips updating in your case
if (version == 0) {
onCreate(db);
} else {
if (version > mNewVersion) {
onDowngrade(db, version, mNewVersion);
} else {
onUpgrade(db, version, mNewVersion);
}
}
db.setVersion(mNewVersion);
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
When version number of db is is 0 the onUpgrade function is not called.
One way to fix the problem is change the version number of db when you add it to the asset or change it before opening
The solution change the version number and your problem
try
{
String myPath = MyApplication.context.getDatabasePath(DATABASE_NAME).toString();
//open a database directly without Sqliteopenhelper
SQLiteDatabase myDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE | SQLiteDatabase.NO_LOCALIZED_COLLATORS);
//if the version is default 0 the update the version
if (myDataBase.getVersion() == 0)
{
//update the database version to the previous one
myDataBase.execSQL("PRAGMA user_version = " + 1);
}
//Close DataBase
myDataBase.close();
}
catch (Exception e)
{
//Do Nothing a fresh install happened
}
Related
In my Android application I'm using the SQLite DB with SQLiteOpenHelper
I have several DB versions, and I've been doing onUpgrade() operations by switching on the old db version, but now I have to remove one of the tables because I'm no longer using it, so should I do something different?
public void onCreate(SQLiteDatabase database) {
database.execSQL(tableUserCreate);
database.execSQL(tableProductsCreate);
database.execSQL(tablePicturesCreate);
}
public void onUpgrade(SQLiteDatabase database, int version_old, int current_version) {
switch (version_old) {
case 1:
database.execSQL(addPostcodeFieldToUserTable);
database.execSQL(tablePlacesCreate);
// Intentional fallthrough, no break;
case 2:
database.execSQL(tableProductVideosCreate);
break;
}
} // End of onUpgrade
Now I want to remove the User table in a new DB version. What do I do?
SQL for dropping a table:
DROP TABLE table_name
Or use:
DROP TABLE IF EXISTS table_name
When you change Database_Version it called
onUpdate(SQLiteDatabase db, int oldVersion, int newVersion)
method first, so you have to do all drop or create kind of stuff inside that method. In your case you use Switch case i do same things using if else.
But both work fine in that case.
if (newVersion == yourNewVersion) {
try {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + YOUR_TABLE_NAME);
// Create tables again IF YOU WANT TO CREATE HERE
} catch (Exception e) {
e.printStackTrace();
}
I have uploaded an apk (version 1.0) with 22 tables in SQLite Database on Google Playstore.
Now i want to update database with 36 tables in new version (version 2.0) of application.
I am storing datebase at default location so when i press "Clear
data" in Application Manager, database is gonna deleted.
I just want to know how to delete old database (same as clear data) when user update new version?
Update:
If is there any solution for clear data while updating application from play store then also answered me.
Your help would be appreciated.
Thanks.
you can use this method to delete your database.
context.deleteDatabase(DATABASE_NAME);
You can also use this method to find your database path first and then delete that.
File myDb = context.getDatabasePath(DATABSE_NAME);
Boolean isDelete = myDb.delete();
The other solution is , if you want to update your database then just change your version number of database. onUpgrade() will automatically get called and your old database will be deleted and new database will be created.
Finally done with simple solution:
/** UPGRADE DATABASE **/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.i(TAG, "Database Version: OLD: "+ oldVersion + " = NEW: "+newVersion);
if(context.deleteDatabase(DATABASE_NAME))
Log.i(TAG, "Database Deleted....");
else
Log.i(TAG, "Database Not Deleted..");
}
Nice Question. Just follow the steps.
1) There are two methods that you override on Your Helper class
#Override
public void onCreate(SQLiteDatabase db) {
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(oldVersion!=newVersion){
// Remove all old tables and crate new ones
}
}
2) create an object of Helper class.
MyOpenHelper dbHelper = new MyOpenHelper(this,"dbname", 1);
3) Now just increase the database version when you want to change the database.(Third argument in MyOpenHelper class. "1" is a database version).
4) When database version changes it will give you a callback in onUograde() method.
5) Remove all tables in onUpgrade() method and create new ones.
6) That's it.
EXPLANATION :
Your app version 1.1 is on google play and your database version is "1". Now you want to upload version 1.2 with new database. Just set database version "2" in your helper file. And check the the oldVersion and newVersion in onUpgrade() method if both are not same that means application updating and remove old tables and create new ones.
If you are using SQLiteOpenHelper just delete your tables in your onUpgrade method and recreate all your tables again. You should have not problems at all.
Check this out.
Hope it helps
Note: Be careful with database versions, if you are playing with your database numbers make sure you have the right number as your oldVersion or it will not work properly when you update your google play.
The obvious solution is to delete the old DB file when onUpgrade() is called and copy the new version over. Too bad it does not work. You get an error something like this:
Caused by: android.database.sqlite.SQLiteReadOnlyDatabaseException: attempt to write a readonly database (code 1032)
SQLiteLog﹕ (1032) statement aborts at 4: [PRAGMA user_version = 2]
SQLiteLog﹕ (28) file unlinked while open: /data/data/my.package/databases/my_db.db
You don't need to delete the database, just copy over it using the method you've alady defined (copyDataBase), like this:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Toast.makeText(myContext, "onUpgrade called!", Toast.LENGTH_LONG).show();
if (oldVersion < newVersion) {
Log.v("Database Upgrade", "Database version higher, upgrading");
try {
copyDataBase();
} catch (IOException e) {
throw new Error("Error upgrading database");
}
}
}
wrok for me, thank
I have seen another question about schema upgrade/migration using green dao (here)
There are lots of links in that answer for a good pattern to use when doing schema upgrades - however there are no examples of what you actually do to your data to migrate it properly and I'm having trouble finding anything.
In my case, my migration is incredibly straight forward - I do not wish to transform any existing data, I simply need to add some new tables to my schema, which I suspect is a fairly common situation.
What is the easiest way to add new tables to your schema without deleting data your users have already saved? A specific example would be greatly appreciated.
It would be awesome if greenDao provided a class similar to DevOpenHelper that would simply add new tables/columns that didn't previously exist in the schema without dropping existing tabes/data first.
I finally had time to dig in to this myself and realized it's quite easy to add a new table while retaining data in old tables.
DISCLAIMER: While I realize this implementation is specific to my scenario, I think it's helpful for someone like me who has used an Android ORM tool (greenDao) exclusively to deal with SQLite on Android. I understand this is pretty common for those of you who have written your own table creation queries from the beginning, but for someone who has been sheltered from the guts of using a SQLite DB with Android, I think this example will be helpful.
ANSWER:
You can either modify the DevOpenHelper inner class or create your own class. I chose to edit DevOpenHelper for the time being to keep my example simple - however, note that if you regenerate your greendao classes, DevOpenHelper will be overwritten. It would be a better idea to create your own class like "MyOpenHelper" and use that instead.
Before my changes, DevOpenHelper.onUpgrade looked like this:
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " + newVersion + " by dropping all tables");
dropAllTables(db, true);
onCreate(db);
}
Instead of dropping all tables, take a look at the createAllTables method that is auto-generated by GreenDao.
Rewrite onUpgrade to check if the "oldVersion" is the one you want to upgrade from, then only call the createTable methods for "new" tables. Here is what my onUpgrade method looks like now:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
Log.i("greenDAO", "Upgrading schema from version " + oldVersion + " to " +
//Going from older schema to new schema
if(oldVersion == 3 && newVersion == 4)
{
boolean ifNotExists = false;
//Leave old tables alone and only create ones that didn't exist
//in the previous schema
NewTable1Dao.createTable(db, ifNotExists);
NewTable2Dao.createTable(db, ifNotExists);
NewTable3Dao.createTable(db, ifNotExists);
NewTable4Dao.createTable(db, ifNotExists);
}
else
{
dropAllTables(db, true);
onCreate(db);
}
}
Adding a new column would be similar, except you'd have to write some SQL or take a look at the auto-generated SQL create statements from greenDao and leverage those.
To add a single new column (NEW_COLUMN, assuming it's an INTEGER type) to an existing table (EXISTING_TABLE), do the following:
db.execSQL("ALTER TABLE 'EXISTING_TABLE' ADD 'NEW_COLUMN' INTEGER");
For me right now, all I needed to do was add new Tables so this ended up being rather straight forward. Hopefully someone else finds this useful.
I made an slightly different approach to handle the updates automatically no matter where the previous user comes from.
First I created a Class that implements the method onUpgrade on a SQLDatabase
public abstract class AbstractMigratorHelper {
public abstract void onUpgrade(SQLiteDatabase db);
}
From this class will inherit all the migrators helpers I will declare afterwards
I will write an example of one of them
public class DBMigrationHelper5 extends AbstractMigratorHelper {
/* Upgrade from DB schema x to schema x+1 */
public void onUpgrade(SQLiteDatabase db) {
//Example sql statement
db.execSQL("ALTER TABLE user ADD COLUMN USERNAME TEXT");
}
}
After this you need to implement the logic on the class that is actually called on upgrade, where you will need to remove the previous DevOpenHelper for a custom one that could look like this
public static class UpgradeHelper extends OpenHelper {
public UpgradeHelper(Context context, String name, CursorFactory factory) {
super(context, name, factory);
}
/**
* Here is where the calls to upgrade are executed
*/
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
/* i represent the version where the user is now and the class named with this number implies that is upgrading from i to i++ schema */
for (int i = oldVersion; i < newVersion; i++) {
try {
/* New instance of the class that migrates from i version to i++ version named DBMigratorHelper{version that the db has on this moment} */
AbstractMigratorHelper migratorHelper = (AbstractMigratorHelper) Class.forName("com.nameofyourpackage.persistence.MigrationHelpers.DBMigrationHelper" + i).newInstance();
if (migratorHelper != null) {
/* Upgrade de db */
migratorHelper.onUpgrade(db);
}
} catch (ClassNotFoundException | ClassCastException | IllegalAccessException | InstantiationException e) {
Log.e(TAG, "Could not migrate from schema from schema: " + i + " to " + i++);
/* If something fail prevent the DB to be updated to future version if the previous version has not been upgraded successfully */
break;
}
}
}
}
So if you are careful naming your Migration Helpers (i.e. MigrationHelper5 does the migration from schema 5 to schema 6) you can implement this logic and then in every MigratorHelper class just implement the execSQL call with all the sql code that you need to implement.
Finally one more remark, if you are working with proguard, the method find name by class might not work, since class names are changed when obfuscating the code. You might want to consider add an exception on the proguard configuration file (proguard-rules.pro) to exclude any class that extend from AbstractMigratorHelper
# Avoid errors when upgrading database migrators
-keep public class * extends yourpackage.locationofyourclass.AbstractMigratorHelper
I do it a slightly different way.
I add my new #DatabaseTable classes and any #DatabaseFields to existing #DatabaseTable classes and run DatabaseConfigUtil.
Then I'll add a new method to my DatabaseUpgrader class and modify my DatabaseHelper, changing the DATABASE_VERSION value and the onUpdate method
public class DatabaseHelper extends OrmLiteSqliteOpenHelper {
private static final int DATABASE_VERSION = 3;
#Override
public void onUpgrade(SQLiteDatabase db, ConnectionSource connectionSource, int oldVersion, int newVersion) {
if (newVersion > oldVersion) {
switch (oldVersion) {
case 1:
DatabaseUpdater.from1to2(connectionSource);
DatabaseUpdater.from2to3(connectionSource);
break;
case 2:
DatabaseUpdater.from2to3(connectionSource);
break;
default:
onCreate(db);
}
}
}
public static DatabaseHelper getInstance() {
return DatabaseHelper.mHelper;
}
public static void setInstance(Context context) {
DatabaseHelper.mHelper = new DatabaseHelper(context);
}
…
}
And then in the DatabaseUpdater class
public class DatabaseUpdater {
private static final String TAG = "DatabaseHelper";
public static void from1to2(ConnectionSource connectionSource) {
try {
DatabaseHelper helper = DatabaseHelper.getInstance();
//Example add a table
TableUtils.createTable(connectionSource, AnotherEntity.class);
} catch (SQLException e) {
Log.e(TAG, "Error upgrading database to v2: ", e);
} catch (java.sql.SQLException e) {
e.printStackTrace();
}
}
public static void from2to3(ConnectionSource connectionSource) {
try {
DatabaseHelper helper = DatabaseHelper.getInstance();
//Example add a field to a table
RuntimeExceptionDao<MyEntity, Integer> myDao = helper.getMyDao();
diaryDao.executeRaw("ALTER TABLE myEntity ADD firstNewField");
diaryDao.executeRaw("ALTER TABLE myEntity ADD anotherNewField");
} catch (SQLException e) {
Log.e(TAG, "Error upgrading database to v3: ", e);
}
}
}
To answer question posted by #MBH on first answer. Also I did not find the answer in this post hence adding.
GreenDAO uses the schema version number from build.gradle file. Gradle file should contain below
android {
...
}
greendao {
schemaVersion 1
}
Refer this link for more information. Then on upgrade change this number to 2 or any increment. Based on that number GreenDAO calls below API from android.database.sqlite.SQLiteDatabase.DatabaseOpenHelper.java
public DatabaseOpenHelper(Context context, String name, int version)
As standard approach by Sqlite DB upgrade, it calls below API
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
As other answers suggest, this method can be overridden in derived class and can handle any project specific upgrades.
Hope this helps.
I am trying to upgrade a certain table by adding a column to a Sqlite table in my android app.I have added an alter table statement in the onUpgrade method of my DBHelper.
Here are the problems that I am seeing
I changed the value of Database version from 1 to 2, so ideally now the onUpgrade should get called.It does get called, but it gets called everytime I instantiate the class.As a result I get a column already exists error.
Here is the onUpgrade method
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.d("old Version",oldVersion+"");
Log.d("New Version",newVersion+"");
db.beginTransaction();
try
{
String DATABASE_UPGRADE;
DATABASE_UPGRADE="alter table "+DATABASE_TABLE_MESSAGES+" ADD COLUMN "+ IS_READ+ " integer DEFAULT 0;";
db.execSQL(DATABASE_UPGRADE);
Log.d("upgrade", "Successful");
db.setTransactionSuccessful();
}
finally
{
db.endTransaction();
}
}
}
I am wondering why the onUpgrade gets called each time!!!
In the constructor of your database helper are you correctly passing the new version number?
EDIT: should look like this
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
and DATABASE_VERSION should be 2.
Typically, for a WinForm or a Web App, I create the database and tables through the RDBMS or through a separate install process. However, I haven't seen anything of the sort in Android. All the examples I've seen have the database creation scripts embedded in an activity like this.
The best thing I can come up with now is to call a method from the data access constructor to check whether the database is installed - if not - install it. However, this seems like a lot of overhead to me.
What's the cleanest way to execute a android database install and then forget about it?
When using SQLLiteOpenHelper (http://developer.android.com/reference/android/database/sqlite/SQLiteOpenHelper.html), the onCreate method will be called only if the database doesn't exist. onUpgrade will be called when a new version of the database is introduced.
IF the database already exists, and no version upgrade occured, these methods won't be executed.
There is no need for implementing if-else checks in your activity.
private static class DatabaseHelper extends SQLiteOpenHelper
{
DatabaseHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
#Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(DATABASE_CREATE);
}
#Override
public void onUpgrade(SQLiteDatabase db, int oldVersion,
int newVersion)
{
Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion);
db.execSQL(DATABASE_UPGRADE);
}
}