Last active
September 26, 2016 05:57
-
-
Save JaydipZala/527859249f61e834eb91c3a430d8f43e to your computer and use it in GitHub Desktop.
Update Existing Table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public void upgradeTable(SQLiteDatabase db) { | |
MyTableHandler mth = new MyTableHandler(); | |
mth.createTable(db); | |
ArrayList<String> columns = getColumns(db, TABLE_NAME); | |
String alterQuery = "ALTER TABLE " + TABLE_NAME + " RENAME TO temp_" + TABLE_NAME; | |
db.execSQL(alterQuery); | |
mth.createTable(db); | |
columns.retainAll(DatabaseHandler.getColumns(db, TABLE_NAME)); | |
String cols = join(columns, ","); | |
db.execSQL(String.format("INSERT INTO %s (%s) SELECT %s FROM temp_%s", | |
TABLE_NAME, cols, cols, TABLE_NAME)); | |
String dropQuery = "DROP TABLE temp_" + TABLE_NAME; | |
db.execSQL(dropQuery); | |
} | |
public ArrayList<String> getColumns(SQLiteDatabase db, String tableName) { | |
ArrayList<String> al = null; | |
Cursor c = null; | |
try { | |
c = db.rawQuery("SELECT * FROM " + tableName + " LIMIT 1", null); | |
if (c != null) { | |
al = new ArrayList<>(Arrays.asList(c.getColumnNames())); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} finally { | |
if (c != null) | |
c.close(); | |
} | |
return al; | |
} | |
public String join(ArrayList<String> al, String delim) { | |
StringBuilder sb = new StringBuilder(); | |
int num = al.size(); | |
for (int i = 0; i < num; i++) { | |
if (i != 0) | |
sb.append(delim); | |
sb.append(al.get(i)); | |
} | |
return sb.toString(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment