我已经尝试了两天并查看了所有不同的帖子。
我也跟着这篇文章。
Steps to upgrade existing Android database w/o losing data
但是当我在手机上安装新版本时,它似乎消灭了我的旧数据。
有人可以请你。
这是我的数据库代码
private static final int DATABASE_VERSION = 2; //was 1 before
public void create() throws IOException{
boolean dbExist = checkDataBase();
if(dbExist){
//do nothing - database already exist
this.getWritableDatabase();
}else{
//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.
try {
this.getReadableDatabase();
copyDataBase();
} catch (IOException e) {
throw new Error("Error copying database");
}
}
}
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if(newVersion == 2) {
db.execSQL("ALTER TABLE CHANNELPROFILE ADD COLUMN backcolor TEXT");
}
}
不确定我在这里做错了什么。请帮忙
答案 0 :(得分:0)
试试这个:
String TABLE_NAME= "train_day";
String column1= "column1";
String column2= "column2";
String column3= "column3";
String TABLE_BODY = TABLE_NAME + " ("
+ column1 + " INTEGER PRIMARY KEY AUTOINCREMENT,"
+ column2 + " TEXT NOT NULL,"
+ column3 + " TEXT NOT NULL)";
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
replaceDataToNewTable(db, TABLE_NAME, TABLE_BODY);
}
private void replaceDataToNewTable(SQLiteDatabase db, String tableName, String tableString){
db.execSQL("CREATE TABLE IF NOT EXISTS " + tableString);
List<String> columns = getColumns(db, tableName);
db.execSQL("ALTER TABLE " + tableName + " RENAME TO temp_" + tableName);
db.execSQL("CREATE TABLE " + tableString);
columns.retainAll(getColumns(db, tableName));
String cols = join(columns, ",");
db.execSQL(String.format("INSERT INTO %s (%s) SELECT %s from temp_%s",
tableName, cols, cols, tableName));
db.execSQL("DROP TABLE temp_" + tableName);
}
private List<String> getColumns(SQLiteDatabase db, String tableName) {
List<String> ar = null;
Cursor c = null;
try {
c = db.rawQuery("select * from " + tableName + " limit 1", null);
if (c != null) {
ar = new ArrayList<String>(Arrays.asList(c.getColumnNames()));
}
} catch (Exception e) {
LOGE(tableName, e.getMessage() + e);
e.printStackTrace();
} finally {
if (c != null)
c.close();
}
return ar;
}
private String join(List<String> list, String divider) {
StringBuilder buf = new StringBuilder();
int num = list.size();
for (int i = 0; i < num; i++) {
if (i != 0)
buf.append(divider);
buf.append(list.get(i));
}
return buf.toString();
}