Room Flashcards
What is Room?
Room is a database library that’s part of Android Jetpack.
Under the hood, the Room library is an abstraction layer on top of a SQLite database.
Instead of using SQLite directly, Room simplifies the chores of setting up, configuring, and interacting with the database.
It also makes it possible for your app to interact with the database using ordinary function calls.
What needs to be added to a data class to make it a Room entity?
1. Annotate the class signature @Entity(tableName = "my_table_name" data class MyEntity(...)
- Annotate the id with a Primary Key
@PrimaryKey(autoGenerate = true)
var myId: Long = 0L - Annotate remaining properties with
@ColumnInfo(name = “my_var_name”)
What does DAO stand for?
What is the DAO?
The Data Access Object can be thought of as a custom interface for accessing your database
Which annotations are needed to create a DAO?
@Dao
interface MyDatabaseDao{ }
@Insert
suspend fun insert(myobject: MyEntity)
@Update
suspend fun update(myobject: MyEntity)
@Query (“SQL COMMAND WHERE myId = :key”) *
suspend fun getOrDeleteEntries(key: Long ): MyEntity? **
*when searching using a parameter (usually the id), use the function’s parameter name with a colon in front to place in the SQL query
**functions need nullable return Types when fetching information
function names do NOT have to match query annotations - they just do in this example for insert and update
Why use a query to clear a table instead of the Room provided @Delete annotation?
@Delete is a useful helper if you know which items need to be removed from the DB - supply it with a list of item id’s to delete.
It is not efficient for clearing all entries.
@Query(“DELETE FROM table_name”)
is cleaner.
It’s a good idea to use which return type when creating a function to fetch all DB entries?
LiveData^List^MyEntity^^
Define the SQL queries for the following:
- fetch a single entry by id
- clear all table entries
- fetch the most recent DB entry
- fetch all entries
1.
(“SELECT * FROM table_name WHERE myID = :key”)
2.
(“DELETE FROM table_name”)
3.
(“SELECT * FROM table_name ORDER BY myId DESC LIMIT 1”)
- (“SELECT * FROM table_name ORDER BY myID DESC”)
The database class is mostly boilerplate, but what are the key things it does?
- @Database(entities = [MyEntity::class], version = 1, exportSchema = false)
2. abstract class MyDatabase : RoomDatabase() { This class is abstract because it is a template for Room to provide the implementation.
- In a companion object, the function getInstance( ) returns a Singleton Database
Explain what these do:
- exportSchema = false
- @Volatile
- synchronized(this){ }
- .fallbackToDestructiveMigration()
.build()
- Schema version history backups do not need to be kept
- Annotated var is only read from main memory - it is not cached - so anything using its value always gets the up-to-date value
- Only one thread can access this block at one time - prevents multiple concurrent instantiations of the DB
- This is a “dummy” migration strategy (it simply destroys and rebuilds the DB) to avoid
What is the syntax used to create a DB instance?
instance = Room.databaseBuilder(
context.applicationContext,
MyDatabase::class.java,
“my_database_name”
)
.fallbackToDestructiveMigration()
.build()
When using Room, why is it a good idea to have your ViewModel extend AndroidViewModel rather than ViewModel?
AndroidViewModel extends ViewModel and is aware of the Application context.
MyDatabase.getInstance( ) takes a context as its only parameter. This is called in Fragment.onCreateview( ).
In Fragment.onCreateView( ), we can create an application variable and pass it to both Database.getInstance( ) and the ViewModelFactory:
val application = requireNotNull(this.activity).application
Why do we not need to specify any Dispatchers when using Room?
Room handles Dispatchers for us.
What is different about fetching DB entries to be returned as LiveData?
The @Query does not need to be specified as a suspend fun because Room automatically handles this on a background thread.
- Which dependencies need to be added to implement Room?
- Which dependency provides extensions and coroutine support for Room?
- And for test helpers?
1.
implementation “androidx.room:room-runtime:$room_version”
kapt “androidx.room:room-compiler:$room_version”
2.
implementation “androidx.room:room-ktx:$room_version”
3.
testImplementation “androidx.room:room-testing:$room_version”
- What Room feature makes handling LiveData easier?
2. How to handle LiveData holding String values to be displayed on the screen?
- A Room @Query returning a LiveData, assigned to a ViewModel variable, will update the variable’s value every time the DB changes.
- Following
val myList = database.getEntries( )
Transform the list
val entriesString = Transformations.map(myList){ entriesList -^ // manipulate entries to String or list of Strings}