Man*_*gde 5 database sqlite android database-update android-sqlite
我正在开发应用程序的第二个版本。我正面临一个问题。
在我的应用程序中,数据库位于资产文件夹中。现在,我想从第二个版本中的assets文件夹更新数据库。
我尝试将代码升级为:
// Data Base Version.
private static final int DATABASE_VERSION = 2;
Run Code Online (Sandbox Code Playgroud)
我将版本从1更改为2。
//构造函数
public DataBaseHelperClass(Context myContext) {
super(myContext, DATABASE_NAME, null ,DATABASE_VERSION);
this.context = myContext;
//The Android's default system path of your application database.
DB_PATH = "/data/data/com.example.myapp/databases/";
}
Run Code Online (Sandbox Code Playgroud)
//创建数据库
public void createDataBase() throws IOException{
//check if the database exists
boolean databaseExist = checkDataBase();
if(databaseExist){
this.getWritableDatabase();
}else{
this.getReadableDatabase();
try{
copyDataBase();
} catch (IOException e){
throw new Error("Error copying database");
}
}// end if else dbExist
} // end createDataBase().
Run Code Online (Sandbox Code Playgroud)
//检查数据库
public boolean checkDataBase(){
File databaseFile = new File(DB_PATH + DATABASE_NAME);
return databaseFile.exists();
}
Run Code Online (Sandbox Code Playgroud)
//从资产复制数据库
private void copyDataBase() throws IOException{
//Open your local db as the input stream
InputStream myInput = context.getAssets().open(DATABASE_NAME);
// Path to the just created empty db
String outFileName = DB_PATH + DATABASE_NAME;
//Open the empty db as the output stream
OutputStream myOutput = new FileOutputStream(outFileName);
//transfer bytes from the input file to the output file
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer))>0){
myOutput.write(buffer, 0, length);
}
//Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
Run Code Online (Sandbox Code Playgroud)
//打开数据库
public void openDataBase() throws SQLException{
//Open the database
String myPath = DB_PATH + DATABASE_NAME;
sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);
}
Run Code Online (Sandbox Code Playgroud)
//关闭数据库
@Override
public synchronized void close() {
if(sqliteDataBase != null)
sqliteDataBase.close();
super.close();
}
@Override
public void onCreate(SQLiteDatabase db) {
// No need to write the create table query.
// As we are using Pre built data base.
// Which is ReadOnly.
}
Run Code Online (Sandbox Code Playgroud)
//在更新数据库上。
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion>oldVersion){
context.deleteDatabase(DATABASE_NAME);
try {
copyDataBase();
} catch (IOException e) {
e.printStackTrace();
}
} else {
}
}
Run Code Online (Sandbox Code Playgroud)
但是问题是,在设备中执行apk后数据库没有更新。现在我该怎么办。
我的应用程序第一个版本在市场上。不知道如何在第二版本中更新数据库。
请为我提供您的宝贵建议,我处于申请的中间位置,无法搬迁。
编辑: onUpgrade不调用。当我尝试在onUpgrade中打印日志的第一行时,却没有打印出来。因此,问题在于onUpgrade没有调用。
| 归档时间: |
|
| 查看次数: |
10087 次 |
| 最近记录: |