我正在开发我的应用程序的第。 我遇到了一个问题。

在我的应用程序中,数据库位于 assets 文件夹中。 现在我想从第二个版本的assets 文件夹中更新我的数据库。

我尝试将代码升级为://Data Base Version.

private static final int DATABASE_VERSION = 2;

我将版本从 1更改为 2.

//Constructorpublic 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/";

}

//创建数据库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().

//检查数据库public boolean checkDataBase(){

File databaseFile = new File(DB_PATH + DATABASE_NAME);

return databaseFile.exists();

}

//从 assets 复制数据库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();

}

//打开数据库public void openDataBase() throws SQLException{

//Open the database

String myPath = DB_PATH + DATABASE_NAME;

sqliteDataBase = SQLiteDatabase.openDatabase(myPath, null, SQLiteDatabase.OPEN_READWRITE);

}

//关闭数据库@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.

}

更新数据库的//。@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 {

}

}

但是问题是,在设备中执行apk之后数据库没有更新。 现在我该怎么做。

我的应用程序的第一个版本在市场上。 不知道如何更新第二个版本中的数据库。

请指引我你的有价值的建议,我正在我的申请中心,我不能移动。

EDIT: onUpgrade未调用。 我试图在onUpgrade中打印 1st 行的日志,但它没有打印。 所以问题是onUpgrade没有呼叫。

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐