问题
I am trying to update my database in my Android application. When I update the version number, onUpgrade gets called, but the version number doesn't increase, so every time I access the database, onUpgrade gets called. Here is my code:
private final static int DB_VERSION = 8;
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DB_VERSION);
this.myContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "in onCreate");
try {
copyDataBase();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "in onUpgrade. Old is: " + oldVersion + " New is: " + newVersion);
myContext.deleteDatabase(DB_NAME);
Log.d(TAG, "the version is " + db.getVersion());
db.setVersion(newVersion);
Log.d(TAG, "the version is " + db.getVersion());
onCreate(db);
}
Anyone know why this is happening?
回答1:
Don't try to manually set the version. (This is all taken care of.)
Don't try to delete the database. You're in the middle of upgrading it, and it shouldn't really surprise you that manually setting the version of a database you've just deleted doesn't work very well.
All you should do in onUpgrade
is make the changes needed to the structure of the tables. If you want to do this by deleting the current tables (NOT the database) and then re-creating them, then that's fine.
If you need to preserve the data in your tables, have a look at this question for suggestions on how to do it: Upgrade SQLite database from one version to another?
回答2:
I ended up adding another database to the assets folder. I know its not the best solution, but it works. When the app is upgraded this time, it just writes the new database - it has a new name - instead of the old one. I check if the old one exists and if it does, I delete it.
来源:https://stackoverflow.com/questions/7534881/onupgrade-database-android-version-number-not-increasing