Last active
December 19, 2015 13:48
-
-
Save ivanvasheka/76ceb4687c3ac0ed8fe3 to your computer and use it in GitHub Desktop.
DB upgrade example
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 class DatabaseHelper extends SQLiteOpenHelper { | |
public static final String DATABASE_NAME = "utilities.db"; | |
private static final int DATABASE_VERSION = 3; | |
public DatabaseHelper(Context context) { | |
super(context, DATABASE_NAME, null, DATABASE_VERSION); | |
} | |
@Override | |
public void onCreate(SQLiteDatabase db) { | |
db.execSQL(Tables.Counters.CREATE); | |
db.execSQL(Tables.Records.CREATE); | |
} | |
@Override | |
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { | |
if (oldVersion < 3) { | |
Calendar calendar = Calendar.getInstance(); | |
db.beginTransaction(); | |
try { | |
String tempRecordsName = Tables.Records.NAME + "_temp"; | |
db.execSQL("ALTER TABLE " + Tables.Records.NAME + " RENAME TO " + tempRecordsName); | |
db.execSQL(Tables.Records.CREATE); | |
Cursor cursor = db.query(tempRecordsName, null, null, null, null, null, null); | |
if (cursor != null) { | |
while (cursor.moveToNext()) { | |
int counterId = cursor.getInt(Tables.Records.INDEX_COUNTER_ID); | |
double value = cursor.getDouble(Tables.Records.INDEX_VALUE); | |
long date = cursor.getLong(Tables.Records.INDEX_DATE); | |
calendar.setTimeInMillis(date); | |
int month = calendar.get(Calendar.MONTH); | |
int year = calendar.get(Calendar.YEAR); | |
ContentValues values = new ContentValues(5); | |
values.put(Tables.Records.COLUMN_COUNTER_ID, counterId); | |
values.put(Tables.Records.COLUMN_VALUE, value); | |
values.put(Tables.Records.COLUMN_DATE, date); | |
values.put(Tables.Records.COLUMN_DATE_MONTH, month); | |
values.put(Tables.Records.COLUMN_DATE_YEAR, year); | |
db.insert(Tables.Records.NAME, null, values); | |
} | |
cursor.close(); | |
} | |
db.execSQL(Tables.DROP + tempRecordsName); | |
db.setTransactionSuccessful(); | |
} finally { | |
db.endTransaction(); | |
} | |
} | |
if (oldVersion < 2) { | |
db.execSQL("ALTER TABLE " + Tables.Counters.NAME + " ADD COLUMN " + Tables.Counters.COLUMN_SOURCE + " TEXT DEFAULT NULL"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment