Once you’ve got your initial model and table set up in your app, you will probably want to modify it somehow later on. Maybe you’ll want to add a column to your table or change a column’s data type. Even though ActiveAndroid gives you a freebie by not making you initially write a script to create your table, you will have to write a migration script for every change to that table. Here’s an example of how to add a column to an existing table:
To start out, I have an Item model that looks like this:
@Table(name = "Items")
public class Item extends Model {
@Column(name = "Name")
private String name;
public Item(){
super();
}
public Item(String name){
super();
this.name = name;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
}
And the application node of my AndroidManifest.xml file contains the following metadata for my database:
<meta-data
android:name="AA_DB_NAME"
android:value="Application.db" />
<meta-data
android:name="AA_DB_VERSION"
android:value="1" />
I would like to add a priority column to my items table. It will only take 3 short steps:
Let’s start by modifying my Item model. Add the new field to the model:
@Table(name = "Items")
public class Item extends Model {
@Column(name = "Name")
private String name;
@Column(name = "Priority")
private String priority;
public Item(){
super();
}
public Item(String name, String priority){
super();
this.name = name;
this.priority = priority;
}
public String getName(){
return name;
}
public void setName(String name){
this.name = name;
}
public String getPriority(){
return priority;
}
public void setPriority(String priority){
this.priority = priority;
}
}
Change the database version in your AndroidManifest.xml. Increment the version by one:
<meta-data
android:name="AA_DB_NAME"
android:value="Application.db" />
<meta-data
android:name="AA_DB_VERSION"
android:value="2" />
The final step is to write your migration script. Name your script [newDatabaseVersion].sql, and place it in the directory [YourApp’sName]/app/src/main/assets/migrations. In my specific example, I’ll create the file [MyAppName]/app/src/main/assets/migrations/2.sql. (You might have to create the migrations directory yourself). You should write the SQLite script to add a column here.
ALTER TABLE Items ADD COLUMN Priority TEXT;
And that’s it! Just note that in order trigger the migration script, you’ll have to save an instance of your model somewhere in your code. For example, I have something like this in my app:
Item item = new Item();
item.setName("do laundry");
item.setPriority("high");
item.save();