我开发了一个在资产文件夹中有数据库的应用程序。数据库在运行时从资产文件夹复制到设备。代码如下:
public class DataBaseHelperClass extends SQLiteOpenHelper{
private final Context context;
private static String DB_PATH = "";
// Data Base Name.
private static final String DATABASE_NAME = "db.sqlite";
// Data Base Version.
private static final int DATABASE_VERSION = 1;
// Table Names of Data Base.
static final String TABLE = "MyTable";
static SQLiteDatabase sqliteDataBase;
@SuppressLint("SdCardPath")
public DataBaseHelperClass(Context context) {
super(context, DATABASE_NAME, null ,DATABASE_VERSION);
this.context = context;
//The Android's default system path of your application database.
DB_PATH = "/data/data/com.abc.myapp/databases/";
}
public void createDataBase() throws IOException{
//check if the database exists
boolean databaseExist = checkDataBase();
if(databaseExist){
this.getWritableDatabase();
}else{
this.getReadableDatabase();
copyDataBase();
}// end if else dbExist
} // end createDataBase().
public boolean checkDataBase(){
File databaseFile = new File(DB_PATH + DATABASE_NAME);
return databaseFile.exists();
}
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) {
}
这段代码工作正常。但现在我对数据库进行了一些更改:
我在数据库中创建了一个新表,
更改记录并在现有表中添加记录。
并将数据库助手类的 onUpdate 更改为:
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion > oldVersion){
//db.execSQL("DROP TABLE IF EXISTS " + DATABASE_NAME);
context.deleteDatabase(DATABASE_NAME);
}
}
并将数据库版本从 1 增加到 2。
生成新的 apk 并安装在设备中。它替换了旧的应用程序并安装了新的应用程序,但数据库中所做的更改没有反映出来。
现在,我应该怎么做才能删除旧版本的数据库并将新数据库从资产文件夹复制到设备中,同时更新应用程序。
请在这个问题上指导我,因为我在谷歌上搜索但没有任何有效的解决方案来删除和更新新数据库。