1

我正在制作一个具有数据库的 Android 应用程序。我能够创建我需要的所有表,但需要用静态数据填充一些表。我尝试通过迁移来执行此操作,但无法按预期运行代码。该应用程序需要此数据才能运行,并且不会更改。创建数据库后立即运行的迁移是否是执行此操作的正确方法?我想确保这些行只创建一次,并且应用程序在创建数据库后永远不需要检查它们的存在。

所有相关的类都在下面。让我知道是否需要更多详细信息。蒂亚!

地位

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;
}

状态枚举

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;
    }
}

静态数据迁移

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));
    }
}
4

0 回答 0