I am using a class to extend SQLiteOpenHelper as follow:
public class PocketSQLite extends SQLiteOpenHelper {
public String TableNames[];
public String FieldNames[][];
public String FieldTypes[][];
public static String NO_CREATE_TABLES = "no tables";
private String message = "";
public PocketSQLite(Context context, String name, CursorFactory factory, int version, String tableNames[], String fieldNames[][], String fieldTypes[][]) {
super(context, name, factory, version);
TableNames = tableNames;
FieldNames = fieldNames;
FieldTypes = fieldTypes;
}
@Override
public void onCreate(SQLiteDatabase db) {
if (TableNames == null) {
message = NO_CREATE_TABLES;
return;
}
for (int i = 0; i < TableNames.length; i++) {
String sql = "CREATE TABLE " + TableNames[i] + "(";
for (int j = 0; j < FieldNames[i].length; j++)
sql += FieldNames[i][j] + " " + FieldTypes[i][j] + ",";
sql = sql.substring(0, sql.length() - 1);
sql += ")";
db.execSQL(sql);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for (int i = 0; i < TableNames[i].length(); i++) {
String sql = "DROP TABLE IF EXISTS " + TableNames[i];
db.execSQL(sql);
}
onCreate(db);
}
}
As you see, the constructor will enter the fields of table. How can I update the onUpgrade function to add a new field to exist table?
For example:
Old Table(2 Fields): “Name”, “Phone”
New Table(3 Fields): “Name”, “Phone”, “Email”
First, You need to change the Database version, when you make such a structural change. And then, in the upgrade method, write your sql statements, which would modify your tables.
When you run your app next time, the onUpgrade method would be called, and your sql statement would be executed, which will modify your table.
http://www.w3schools.com/sql/sql_alter.asp
You can drop the table as well, but as you said, you will lose the existing data.