感谢Joe Masilotti对这个答案的感谢 http://www.reigndesign.com/blog/using-your-own-sqlite-database-in-android-applications/comment-page-2/
private static final int DATABASE_VERSION = 1;
更改构造函数:
public DataBaseHelper(Context context) {
super(context, DB_NAME, null, DATABASE_VERSION);
this.myContext = context;
}
更改createDataBase
到(感谢@kondortek):
public void createDataBase() throws IOException {
boolean dbExist = checkDataBase();
if (dbExist) {
Log.v(“DB Exists”, “db exists”);
// By calling this method here onUpgrade will be called on a
// writeable database, but only if the version number has been
// bumped
this.getWritableDatabase();
}
dbExist = checkDataBase();
if (!dbExist) {
// By calling this method and empty database will be created into
// the default system path of your application so we are gonna be
// able to overwrite that database with our database.
this.getReadableDatabase();
try {
copyDataBase();
} catch (IOException e) {
throw new Error(“Error copying database”);
}
}
}
更改onUpgrade
到:
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (newVersion > oldVersion)
Log.v(“Database Upgrade”, “Database version higher than old.”);
myContext.deleteDatabase(DB_NAME);
}
为什么dbExist被调用了两次?通过调用boolean dbExist = checkDataBase();我们已经知道是否存在数据库。为什么我们不这样做,而不是再次调用相同的方法 - > dbExist = checkDataBase(); ? – 2012-10-25 12:00:28
call copyDataBase();在onUpgrade(...)方法中(在删除旧的数据库之后),以便不需要检查dbExist = checkDataBase();第二次。 – selva 2013-02-13 05:36:38