Add Entity Classes

Kotlin and Android Development featuring Jetpack — by Michael Fazio (42 / 125)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Create a DAO Class | TOC | Add Data During Database Creatio n 👉

Entity classes are the tables in our Room database. By adding the @Entity annotation and a bit of configuration, we can convert a normal data class into a Room Entity. In case you’re wondering, we’ll be putting all the new classes in the data package.

We’re going to start with the Game that was used in the PennyDropDao class. This class will hold all the required information about a given game of Penny Drop but none of the player info. If we’re thinking about the real-life game, this represents the holder where the pennies are placed.

The Game class will contain a bunch of info: game start/end times, the game state, filled slots, the previous roll value, the turn text, and whether or not players can roll and pass. It will also have a gameId value, which will be the primary key in the database. Finally, we need to annotate the class with the @Entity annotation, which includes the name of the associated database table.

​ @Entity(tableName = ​"games"​)
​ ​data class​ Game(
​ @PrimaryKey(autoGenerate = ​true​) ​var​ gameId: Long = 0,
​ ​val​ gameState: GameState = GameState.Started,
​ ​val​ startTime: OffsetDateTime? = OffsetDateTime.now(),
​ ​val​ endTime: OffsetDateTime? = ​null​,
​ ​val​ filledSlots: List<Int> = emptyList(),
​ ​val​ lastRoll: Int? = ​null​,
​ ​val​…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.