/Room_basic_project

Learning how to use Room

Primary LanguageKotlinApache License 2.0Apache-2.0

Room_basic_project

Learning how to use Room Notes

Intergation

  • adding dependencies in app gradle file
  • applying kapt plugin
  • using kapt for annotation processor in Kotlin
  • making sure that we include jcenter and google repositories int he top level gradle file

Creation of the database

  • Create an abstract class that will extend RoomDatabase class
  • Specify the version number. Everytime changing the database, change the number of the version. Otherwise will get runtime exception.
  • Define the entities, after defining the version
  • Make sure the database is a singletone instance
  • When creating the database we shuld use application context
  • Create a property of the database and get its instance in the onCreate method of MainActivity
  • In order to compile the app we need to add at least one entity.

Defining an entity

  • An entity is something you want to store in the database
  • We define the entity in the code level
  • Room handles the creation of SQLite tables for each entity
  • We need to add @Entity annotation to make a class (or data class in Kotlin) an Entity
  • If there is an Id property it can make sense to make it as a @PrimaryKey that can be unique for each object tha will be stored in the database
  • @PrimeryKey can be set to be autogenerated = true. In this case it should be var in Kotlin and not val, and hold the type of Int or Long
  • Val should be changed to var because Room needs to generate and work with setters.
  • Register the entity in the DataBase file

Customising the names of tables and columns

  • Room will create the table name as specified in the Entity class name.
  • After building the project the Room generates the file with the Databasename_Impl.
  • There we can see the tables that the Room created
  • To customise the table name, specify the name in the brackets at @Entity(tableName = "CustomTableName")
  • Column names can be also customised by adding @ColumnInfo(name = "someName") to the properties of the Entity class

Creating Data Access object

-In order to interact with the database Room uses the Data Access Object pattern

  • DAO is an object which serves as a gateway between the database and the rest of the app. Interaction operations such as read or write will go through DAO object
  • DAO can be defined as an interface or abstract class
  • Room will generate the necessary object at compile time
  • In database class make abstract function to return the DAO object.
  • Instantiate dao object from the database in onCreate in MainActivity