I am making an Android app that has a database. I am able to create all the tables I need but need to populate some tables with static data. I tried doing this with a migration but cannot get the code to run as I expect. This data is needed for that app to run and will not change. Is a migration that runs immediately after the database is created the correct way to do this? I want to be sure that the rows only get created once and the app will never need to check for their existence after the database is created.
All the relevant classes are below. Let me know if any more details are needed. TIA!
Status
import androidx.annotation.NonNull;
import androidx.room.Entity;
import androidx.room.Index;
import androidx.room.PrimaryKey;
@Entity(tableName = "Status", indices = { @Index(value = {"Name"}, unique = true) })
public class Status
{
@PrimaryKey(autoGenerate = true)
public int Id;
@NonNull
public String Name;
}
StatusEnum
public enum StatusEnum
{
New(1, "New"),
InProgress(2, "In Progress"),
Closed(3, "Closed");
public final int Id;
public final String Name;
StatusEnum(int id, String name)
{
Id = id;
Name = name;
}
}
StaticDataMigration
import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
import android.os.Build;
import androidx.annotation.RequiresApi;
import androidx.room.Database;
import androidx.room.Room;
import androidx.room.RoomDatabase;
import androidx.room.migration.Migration;
import androidx.sqlite.db.SupportSQLiteDatabase;
@RequiresApi(api = Build.VERSION_CODES.O)
@Database(entities = { Status.class }, version = 2, exportSchema = false)
public abstract class StaticDataMigration extends RoomDatabase
{
public static final Migration MIGRATION_1_2 = new Migration(1, 2)
{
@Override
public void migrate(SupportSQLiteDatabase database)
{
sql = "INSERT INTO Status VALUES ";
for (StatusEnum enumType : StatusEnum.values())
{
sql = sql + String.format("(%d, %s),", enumType.Id, enumType.Name);
}
sql = removeLastChar(SQL);
database.beginTransaction();
database.execSQL(sql);
database.endTransaction();
Room.databaseBuilder(getApplicationContext(), MyDatabase.class, "MyDatabase").addMigrations(MIGRATION_1_2).build();
}
//Room.databaseBuilder(Context, MyDatabase.class, "MyDatabase").addMigrations(MIGRATION_1_2).build();
//Database.mig(Context, MyDatabase., "MyDatabase").addMigrations(MIGRATION_1_2).build();
};
private static String removeLastChar(String s)
{
return (s == null || s.length() == 0) ? null : (s.substring(0, s.length() - 1));
}
}