I m using SQLite database of Android to save text. I earlier had 2 columns and the table was crated like this
db.execSQL("create table Storage(id integer PRIMARY KEY AUTOINCREMENT,title text,body text)");
Afterwards I had a need of adding a new column so i just added a new line in the above code anf then it looked like this
db.execSQL("create table EasyPadStorage(id integer PRIMARY KEY AUTOINCREMENT,title text,body text,color text)"); //Added a column named colors
Now whenever i start the app it throws the crash message saying my app has unfortunately closed. I did some research and found a few soultions but no one helped. I used the following onUpgrade methods
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1 && newVersion == 2) {
db.execSQL("DROP TABLE IF EXISTS" + Tablename);
db.execSQL("DROP TABLE IF EXISTS" + Tablename2);
onCreate(db);
}
}
I do not have any hesitation to use drop the table but if ALTER could work please guide me how to. Either by dropping the table or by using ALTER i just want that my app doesn't crash because of upgrade in tables When i push the update. My database class earlier looked like.
public class SaveN extends SQLiteOpenHelper {
public static final String Databasename = "easypad.db";
public static final String Title = "title";
public static final String Body = "body";
public static final String Tablename = "EasyPadStorage";
public static final String Tablename2 = "details";
Context context;
public SaveN(Context context) {
super(context, Databasename, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table Storage(id integer PRIMARY KEY AUTOINCREMENT,title text,body text)");
db.execSQL("create table details(name text,image blob)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
db.execSQL("DROP TABLE IF EXISTS" + Tablename);
db.execSQL("DROP TABLE IF EXISTS" + Tablename2);
}
And Now after the changes I've made and methods I've tried to not let my App crash(but failed) looks like this
public SaveN(Context context) {
super(context, Databasename,null,DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("create table Storage(id integer PRIMARY KEY AUTOINCREMENT,title text,body text,color text)");
db.execSQL("create table details(name text,image blob)");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
if (oldVersion == 1 && newVersion == 2) {
db.execSQL("DROP TABLE IF EXISTS" + Tablename);
db.execSQL("DROP TABLE IF EXISTS" + Tablename2);
onCreate(db);
}
}
Aucun commentaire:
Enregistrer un commentaire