0

i have an android project in progress where the user will have the chance to play some games like tik tak toe, Rock–paper–scissors etc. For the database I use Room persistence so i want to create 12 instances one for each game. Each game has name, targetSkill etc etcGame tic_tac_toe = new Game("tic tac toe", "attention"....) . I would like to create these 12 instances when the user install the app and then store them in the database. I don't know how to do this. Where i should place the code for the instances in order to run once?? Here is the model for the game (Game class)

@Entity(tableName = "games")
public class Game {

    @PrimaryKey(autoGenerate = true)
    @NonNull
    private int id;

    @ColumnInfo(name = "name")
    @NonNull
    private String name;

    @ColumnInfo(name = "targetSkill")
    @NonNull
    private String targetSkill;

    @ColumnInfo(name = "description")
    @NonNull
    private String description;

    @ColumnInfo(typeAffinity = ColumnInfo.BLOB)
    private byte[] image;

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    @NonNull
    public String getName() {
        return name;
    }

    public void setName(@NonNull String name) {
        this.name = name;
    }

    @NonNull
    public String getTargetSkill() {
        return targetSkill;
    }

    public void setTargetSkill(@NonNull String targetSkill) {
        this.targetSkill = targetSkill;
    }

    @NonNull
    public String getDescription() {
        return description;
    }

    public void setDescription(@NonNull String description) {
        this.description = description;
    }

    public byte[] getImage() {
        return image;
    }

    public void setImage(byte[] image) {
        this.image = image;
    }

    public Game(@NonNull String name, @NonNull String targetSkill, @NonNull String description) {
        this.name = name;
        this.targetSkill = targetSkill;
        this.description = description;
    }

    @Ignore
    public Game(@NonNull String name, @NonNull String targetSkill, @NonNull String description, byte[] image) {
        this.name = name;
        this.targetSkill = targetSkill;
        this.description = description;
        this.image = image;
    }
}

i have also one more java Class called Game Helper where i create the inastances for the games

String stoneDesc = "the screen displays 2 images (rock, paped, scissor) and the user has to pick " + "the appropriate image. It depends on Lose or Win Mode";

Game Rock =new Game("Rock","skill",stoneDesc,logoImage);
Zoe
  • 27,060
  • 21
  • 118
  • 148
VasilisK
  • 87
  • 1
  • 5

2 Answers2

1

You just need to prepopulate your database like this:

  1. AppDatabase:

@Database(entities = {City.class, WeekForecastItem.class, CurrentForecast.class}, version = 1) public abstract class AppDatabase extends RoomDatabase {

    private static AppDatabase INSTANCE;

    public abstract CityDao cityDao();

    public abstract WeekForecastItemDao weekForecastItemDao();

    public abstract CurrentForecastDao currentForecastDao();

    public synchronized static AppDatabase getInstance(Context context) {
        if (INSTANCE == null) {
            INSTANCE = buildDatabase(context);
        }
        return INSTANCE;
    }

    private static AppDatabase buildDatabase(final Context context) {
        return Room.databaseBuilder(context,
                AppDatabase.class,
                "my-database")
                .addCallback(new Callback() {
                    @Override
                    public void onCreate(@NonNull SupportSQLiteDatabase db) {
                        super.onCreate(db);
                        Executors.newSingleThreadScheduledExecutor().execute(new Runnable() {
                            @Override
                            public void run() {
                                getInstance(context).cityDao().insertAll(City.populateCityData());
                            }
                        });
                    }
                })
                .build();
    }
    }`
  1. And the class we will use as a data model, it could be a Game class in your case (notice, it has the populateCityData() method):

@Entity public class City {

    @PrimaryKey(autoGenerate = true)
    public long id;

    public String name;

    public int woeid;

    public City(String name, int woeid) {
        this.name = name;
        this.woeid = woeid;
    }

    public static City[] populateCityData() {
        return new City[]{
                new City("Saint-Petersburg", 2123260),
                new City("Moscow", 2122265),
        };
    }

    public void setId(long id) {
        this.id = id;
    }

    public long getId() {
        return id;
    }

    public String getName() {
        return name;
    }

    public int getWoeid() {
        return woeid;
    }
    }`

It worked for me project with similar task)

0

There are two ways you could do this in Room.

  1. You could create a migration that adds these hard coded games. This way when the app connects to the database the first time it will run your insert code. The drawback to this approach is you can't use the DAO you have to run raw sql. But you are guaranteed to only have one instance of each since that migration will only run between database versions.

  2. In your launching activity you can run a task(Coroutine, AsyncTask,...) that will first check for the games to be there and then insert them if absent. It requires upto 2 queries per game but it lets you add more games on the fly without updating the database version.

I prefer number 2 myself it is a little more processing but much more flexible.

Ge3ng
  • 1,875
  • 1
  • 24
  • 38