Chapters

Hide chapters

Saving Data on Android

Second Edition · Android 11 · Kotlin 1.5 · Android Studio 4.2

Using Firebase

Section 3: 11 chapters
Show chapters Hide chapters

7. Entity Definitions
Written by Subhrajyoti Sen

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Heads up... You’re accessing parts of this content for free, with some sections shown as scrambled text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In the previous chapter, you learned the architecture best suited for Room. You also learned about ORMs, Android Architecture Components and the advantages and disadvantages of SQLite.

In this chapter, you’ll cover all you need to know about Room entities. Along the way, you’ll learn:

  • The properties of SQLite tables.
  • How to add Room’s dependencies to your Gradle files.
  • How to create SQLite tables using Room annotations.
  • How to define primary keys and column names.

Hopefully, you’re ready to get started!

Note: This chapter assumes you have a basic knowledge of Kotlin and Android. If you’re new to Android, you can find a lot of beginner Android content to get you started on our site at https://www.raywenderlich.com/category/android. If you know Android, but are unfamiliar with Kotlin, take a look at our tutorial, “Kotlin for Android: An Introduction” at https://www.raywenderlich.com/174395/kotlin-for-android-an-introduction-2.

Getting started

Have you ever played trivia games and thought, “There should be a game like this but with questions for Android developers”? Well, the sample app you’ll be working on, DroidQuiz, is a trivia game that allows you to answer a series of questions to test your knowledge of Android.

In this chapter, you’re going to build entities that represent the tables of your database. If you’ve had some previous experience with SQL, you probably know this can be somewhat annoying or painstaking to accomplish. Additionally, in “Chapter 3, SQLite Database,” you saw how, with SQL syntax, it can sometimes be hard to deduce which parts of it caused an error (if by some chance you get one). The Room database, and its annotation-driven system of creating entities and queries, make this process tremendously easier.

Start by opening the starter project for this chapter in Android Studio 4.2 or greater. Go to File ▸ Open, find app folders in the entity-definitions ▸ projects folder, and select the starter directory.

Once the starter project finishes loading and building, run the app on a device or an emulator.

Starting Screen of the Sample App.
Starting Screen of the Sample App.

Right now, the app is just an empty canvas, but that is about to change!

Tables and entities

Most databases consist of tables and entities. If you were to draw a parallel with object-oriented programming, you could think of entities as a class definition, which defines what the objects in the table should look like and how their respective properties behave. Once you create those objects — instances of classes, or entities in your case — you can store them somewhere in memory, which is the table. The table as such is a container for all the created objects of some entity type.

Tables

If you reached this section of the book you’re probably already familiar with relational databases, tables and SQLite. However, it’s important to review other key concepts before you proceed to create your entities using Room.

Example of a Movie Table.
Osutpvu oq a Huneo Duzxa.

Columns

Columns represent a field or property of your data like the Title, Description, ReleaseDate or Rating. Columns usually have specific data types such as INTEGER, VARCHAR, FLOAT or DATETIME that help preserve the integrity of the information stored in your database.

Example of an Orders Table.
Oxontmo ac ux Ocyozc Womju.

Rows

Rows represent a record in your database and can contain as many columns as needed to represent your data. Row and record are terms that are often used interchangeably just like column and field. However, when creating a database, you’ll need to make sure that your team is on the same page regarding naming conventions.

Entities

To create a table using Room you need to create an entity, just like you did above. Entities in Room are defined by using a series of different annotations on classes. The following are the most common annotations that you will use when defining an entity:

@Entity declares that the annotated class is a Room entity. For each entity, a table is created in the associated SQLite database to save your data. To add the annotation, simply use the following approach:

@Entity
data class Movie(
    //...
)
@Entity(tableName = "movies")
data class Movie(
    //...
)

@PrimaryKey allows you to define a primary key for your table. It’s very important to remember that each entity in Room must have at least one field defined as the primary key:

@Entity
data class Movie(
  @PrimaryKey var id: Int,
  var title: String?,
  var description: String?,
  var releaseDate: String?,
  var rating: Float
)
@Entity
data class Movie(
  @PrimaryKey(autogenerate = true) var id: Int,
  var title: String?,
  var description: String?,
  var releaseDate: String?,
  var rating: Float
)

In the same way that the tableName property of @Entity allows you to customize the name of your table, @ColumnInfo lets you change the name of your columns — class properties in Kotlin:

@Entity
data class Movie(
  @PrimaryKey(autogenerate = true) var id: Int,
  var title: String?,
  var description: String?,
  @ColumnInfo(name = "release_date") var releaseDate: String?,
  var rating: Float
)

Room translates all of your class properties into database columns by default. If there is a field that you don’t want to be converted into a column, you can use @Ignore to tell Room to ignore it:

@Entity
data class Movie(
  @PrimaryKey(autogenerate = true) var id: Int,
  var title: String?,
  var description: String?,
  @ColumnInfo(name = "release_date") var releaseDate: String?,
  var rating: Float,
  @Ignore var poster: Bitmap?
)
@Entity(ignoredColumns = arrayOf("poster"))
data class Movie(
  @PrimaryKey(autogenerate = true) var id: Int,
  var title: String?,
  var description: String?,
  @ColumnInfo(name = "release_date") var releaseDate: String?,
  var rating: Float,
  var poster: Bitmap?
)

You use @Embedded on an entity’s field to tell Room that the properties on the annotated object should be represented as columns on the same entity.

@Entity
data class User(
  @PrimaryKey val id: Int,
  val firstName: String?,
  val street: String?,
  val state: String?,
  val city: String?,
  @ColumnInfo(name = "post_code") val postCode: Int
)
data class Address(
    val street: String?,
    val state: String?,
    val city: String?,
    @ColumnInfo(name = "post_code") val postCode: Int
)

@Entity
data class User(
    @PrimaryKey val id: Int,
    val firstName: String?,
    @Embedded val address: Address?
)

Creating your entities

Since you’ll be working on with Room, you need to add the appropriate dependencies to your build.gradle files to use Room. To ensure forward compatibility with future versions of Android, you’ll use Androidx artifacts for this project.

//Room
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
Verifying that The App shows The Main Screen.
Dinozrodz spet Lhe Umk ssokt Xpo Geen Twmuoy.

Creating a New Package - Data
Mveikucb i Lal Zoxfoye - Dogu

Creating a New Package - Model
Rfeivabj i Qac Figgapu - Vayiw

Entity Relationship Diagram
Iltujx Yovaqueztxiy Tuekwew

@Entity(tableName = "questions") // 1
data class Question(
  @PrimaryKey(autoGenerate = true) // 2
  @ColumnInfo(name = "question_id") // 3
  var questionId: Int,
  val text: String
)
@Entity(tableName = "answers")
data class Answer(
  @PrimaryKey(autoGenerate = true)
  @ColumnInfo(name = "answer_id")
  val answerId: Int,
  @ColumnInfo(name = "question_id")
  val questionId: Int,
  @ColumnInfo(name = "is_correct")
  val isCorrect: Boolean,
  val text: String
)

Creating the database

Create a new package under the data directory and name it db.

Project Structure
Dsomabr Scserqeno

@Database(entities = [(Question::class), (Answer::class)], version = 1)
abstract class QuizDatabase : RoomDatabase()
//1
class QuizApplication : Application() {

  private val DB_NAME = "quiz_database"

  companion object {
    lateinit var database: QuizDatabase // 2
      private set
  }

  override fun onCreate() {
    super.onCreate()
    database = Room
      .databaseBuilder(
        this,
        QuizDatabase::class.java,
        DB_NAME
      ) // 3
      .build()
  }
}
android:name=".QuizApplication"
Final Screen.
Fefey Tmhuol.

Key points

Where to go from here?

In this chapter, you learned a lot about SQLite tables, Room and entities. If you want to learn more about entities, I suggest the following resources:

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.

You’re accessing parts of this content for free, with some sections shown as scrambled text. Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now