Skip to content

Instantly share code, notes, and snippets.

@mlnkrish
Last active August 14, 2018 10:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mlnkrish/eeed1cfa9c11f6d37841 to your computer and use it in GitHub Desktop.
Save mlnkrish/eeed1cfa9c11f6d37841 to your computer and use it in GitHub Desktop.
Managing database migrations for Android
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import java.util.List;
public class DatabaseOpenHelper extends SQLiteOpenHelper {
final private static String NAME = "your_db";
final private static Integer VERSION = Migrations.migrations.size();;
public DatabaseOpenHelper(Context context) {
super(context, NAME, null, VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
for (int i = 0; i < VERSION; i++) {
executeMigration(db, i);
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
for (int i = oldVersion; i < newVersion; i++) {
executeMigration(db, i);
}
}
private void executeMigration(SQLiteDatabase db, int version) {
List<String> migration = Migrations.migrations.get(version);
for (String sql : migration) {
db.execSQL(sql);
}
}
}
import java.util.Arrays;
import java.util.List;
public class Migrations {
private static final String CREATE_USER = "CREATE TABLE users (id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "identity TEXT NOT NULL UNIQUE, "
+ "first_name TEXT NOT NULL, "
+ "last_name TEXT NOT NULL, "
+ "mobile TEXT NOT NULL UNIQUE, "
+ "email TEXT NULL, "
+ "designation TEXT NULL, "
+ "company_name TEXT NULL, "
+ "website TEXT NULL)";
private static final String CREATE_CONTACTS = "CREATE TABLE contacts (id INTEGER PRIMARY KEY AUTOINCREMENT, "
+ "identity TEXT NOT NULL,"
+ "first_name TEXT NOT NULL, "
+ "last_name TEXT NOT NULL, "
+ "designation TEXT NULL, "
+ "company_name TEXT NULL, "
+ "website TEXT NULL, "
+ "twitter TEXT NULL, "
+ "linked_in TEXT NULL, "
+ "notes TEXT NULL, "
+ "mobile TEXT NOT NULL UNIQUE, "
+ "dirty INTEGER NOT NULL,"
+ "edition_id INTEGER NOT NULL,"
+ "email TEXT NULL)";
private static List<String> migrations0 = Arrays.asList(CREATE_USERS,
CREATE_CONTACTS
);
private static final String CREATE_USER_ITEMS = "CREATE TABLE user_items (id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, " +
"edition_id INTEGER NOT NULL," +
"item_id TEXT NOT NULL UNIQUE," +
"dirty INTEGER NOT NULL," +
"value TEXT NOT NULL)";
private static List<String> migrations1 = Arrays.asList(CREATE_USER_ITEMS);
public static List<List<String>> migrations = Arrays.asList(migrations0,migrations1);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment