在我的数据库的第一个版本中,我有三行。以下方法属于扩展SQLiteOpenHelper
的类。
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE " + DATABASENAME + " (name TEXT, latitude REAL, longitude REAL);");
}
现在,我已将版本号从1更改为2,并添加了一个新行:
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE " + DATABASENAME + " (name TEXT, latitude REAL, longitude REAL, country TEXT);");
}
我不关心旧数据库丢失,所以我在升级时使用它:
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.delete(DATABASENAME, null, null);
onCreate(db);
}
现在,当我调用方法getReadableDatabase()
时,应用程序崩溃,导致logcat错误
引起:android.database.sqlite.SQLiteException:无法升级 版本1到2的只读数据库: /data/data/com.myapp.app/databases/mydb
我该如何防止这种情况?
修改
全班:
public class StationsOpenHelper extends SQLiteOpenHelper {
private static final String DATABASENAME = "stations";
private static final int DATABASEVERSION = 2;
public StationsOpenHelper(Context context) {
super(context, DATABASENAME, null, DATABASEVERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
database.execSQL("CREATE TABLE " + DATABASENAME + " (name TEXT, latitude REAL, longitude REAL, country TEXT);");
}
@Override
public void onUpgrade(SQLiteDatabase db, int arg1, int arg2) {
db.delete(DATABASENAME, null, null);
onCreate(db);
}
public ArrayList<Station> getStations() {
Logger.log("Trying to read stations from database");
ArrayList<Station> result = new ArrayList<Station>();
SQLiteDatabase database = getReadableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM " + DATABASENAME, null);
String name, country;
double lat, lon;
Station s;
cursor.moveToFirst();
while (!cursor.isAfterLast()) {
s = new Station();
name = cursor.getString(0);
lat = cursor.getDouble(1);
lon = cursor.getDouble(2);
country = cursor.getString(3);
s.setName(name);
s.setLatitude(lat);
s.setLongitude(lon);
s.setCountry(country);
result.add(s);
cursor.moveToNext();
}
cursor.close();
database.close();
if (result.isEmpty()) {
Logger.log("Reading stations from database failed");
result = null;
} else {
Logger.log("Reading stations from database succeeded");
}
return result;
}
public void storeStations(ArrayList<Station> stations) {
Logger.log("Storing stations in database");
ContentValues values = new ContentValues();
SQLiteDatabase db = getWritableDatabase();
db.delete(DATABASENAME, null, null);
for (int i = 0; i < stations.size(); i++) {
values.put("name", stations.get(i).getName());
values.put("latitude", stations.get(i).getLatitude());
values.put("longitude", stations.get(i).getLongitude());
values.put("country", stations.get(i).getCountry());
db.insert(DATABASENAME, null, values);
}
db.close();
Logger.log("Storing stations in database succeeded");
}
}
答案 0 :(得分:13)
好的,这是我建议的解决方案,将db.delete替换为:
db.execSQL("DROP TABLE IF EXISTS " + DATABASENAME);
我有一种奇怪的感觉会起作用;)