Local Storage Data
Android Development with Kotlin v1.0 This work is licensed under the Apache 2 license. 1
About this lesson
Local Storage Data
● Storing data
● Room persistence library
Android Development with Kotlin This work is licensed under the Apache 2 license. 2
Storing data
So far, the apps we’ve created primarily display data that was stored in memory in
our apps. We can build a far more useful app if we learn how to persist data in
local storage on the device in a scalable and flexible way.
Android Development with Kotlin This work is licensed under the Apache 2 license. 3
Ways to store data in an Android app
● App-specific storage: Store files that are meant for your app's use only.
● Shared storage (files to be shared with other apps)
● Preferences: Store private, primitive data in key-value pairs.
● Databases: Store structured data in a database that’s private to your app.
Android Development with Kotlin This work is licensed under the Apache 2 license. 4
What is a database?
Collection of structured data that can be easily accessed,
searched, and organized, consisting of:
Example Database
● Tables
● Rows person car
● Columns _id _id
name make
age model
This is a relational database. email year
5
Android Development with Kotlin This work is licensed under the Apache 2 license.
Structured Query Language (SQL)
Use SQL to access and modify a relational database.
● Create new tables
● Query for data
● Insert new data
● Update data
● Delete data
Android Development with Kotlin This work is licensed under the Apache 2 license. 6
SQLite in Android
Because mobile devices are limited
Store data in terms of hardware and computing
capabilities, Android uses SQLite,
Your app
which is based on the SQL standard.
SQLite is lightweight, open-source,
and ideal for embedded devices,
and what you will be using to store data
SQLite database
in a database in your Android app.
Android Development with Kotlin This work is licensed under the Apache 2 license. 7
Example SQLite commands
Create
INSERT INTO colors VALUES ("red", "#FF0000");
Read
SELECT * from colors;
Update
UPDATE colors SET hex="#DD0000" WHERE name="red";
Delete
DELETE FROM colors WHERE name = "red";
Android Development with Kotlin This work is licensed under the Apache 2 license. 8
Interacting directly with a database
● No compile-time verification of raw SQL queries
● Need lots of boilerplate code to convert between
SQL queries data objects
Fortunately, Android Jetpack introduced the Room persistence library,
which offers a layer of abstraction that lets you more easily interact with
a database in your app.
Android Development with Kotlin This work is licensed under the Apache 2 license. 9
Room persistence library
The Room persistence library provides an abstraction layer over SQLite to
allow for more robust database access, while harnessing the full power of SQLite.
Android Development with Kotlin This work is licensed under the Apache 2 license. 10
Add Gradle dependencies
dependencies {
implementation "androidx.room:room-runtime:$room_version"
kapt "androidx.room:room-compiler:$room_version"
// Kotlin Extensions and Coroutines support for Room
implementation "androidx.room:room-ktx:$room_version"
// Test helpers
testImplementation "androidx.room:room-testing:$room_version"
}
Android Development with Kotlin This work is licensed under the Apache 2 license. 11
Room
Rest of the app code
Color("#FF0000", "red")
Room
Colors Data access object Color("#4CAF50", "green")
database
Color("#1155CC", "blue")
Room is an object relational mapping library that converts data from their representation
in a database into objects that we can directly manipulate in the app code. It can also
reverse the process, pushing data from the objects back to the database.
Android Development with Kotlin This work is licensed under the Apache 2 license. 12
ColorValue app
Android Development with Kotlin This work is licensed under the Apache 2 license. 13
Room
There are three major components in Room:
● Entity: Represents a table within the database (Color)
● DAO: Contains the methods used for accessing the database
(ColorDao)
● Database: Contains database holder, and is the main access point
for the underlying connection to the app's persisted, relational data
(ColorDatabase)
In the ColorValue app, we will declare three classes: Color, ColorDao, and ColorDatabase.
Android Development with Kotlin This work is licensed under the Apache 2 license. 14
Color class
data class Color {
val hex: String,
val name: String
}
Android Development with Kotlin This work is licensed under the Apache 2 license. 15
Annotations
● Provide extra information to the compiler
@Entity marks entity class, @Dao for DAO, @Database for database
● Can take parameters
@Entity(tableName = "colors")
● Can autogenerate code for you
Android Development with Kotlin This work is licensed under the Apache 2 license. 16
Entity
Class that maps to a SQLite database table
● @Entity
● @PrimaryKey
● @ColumnInfo
Android Development with Kotlin This work is licensed under the Apache 2 license. 17
Example entity
@Entity(tableName = "colors") colors
data class Color { _id
hex_color
@PrimaryKey(autoGenerate = true) val _id: Int,
name
@ColumnInfo(name = "hex_color") val hex: String,
val name: String
}
Android Development with Kotlin This work is licensed under the Apache 2 license. 18
Data access object (DAO)
Work with DAO classes instead of accessing database directly:
● Define database interactions in the DAO.
● Declare DAO as an interface or abstract class.
● Room creates DAO implementation at compile time.
● Room verifies all of your DAO queries at compile-time.
Android Development with Kotlin This work is licensed under the Apache 2 license. 19
Example DAO
@Dao
interface ColorDao {
@Query("SELECT * FROM colors")
fun getAll(): Array<Color>
@Insert
fun insert(vararg color: Color)
@Update
fun update(color: Color)
@Delete
fun delete(color: Color)
Android Development with Kotlin This work is licensed under the Apache 2 license. 20
Query
@Dao
interface ColorDao {
@Query("SELECT * FROM colors")
fun getAll(): Array<Color>
@Query("SELECT * FROM colors WHERE name = :name")
fun getColorByName(name: String): LiveData<Color>
@Query("SELECT * FROM colors WHERE hex_color = :hex")
fun getColorByHex(hex: String): LiveData<Color>
Android Development with Kotlin This work is licensed under the Apache 2 license. 21
Insert
@Dao
interface ColorDao {
...
@Insert
fun insert(vararg color: Color)
...
}
Android Development with Kotlin This work is licensed under the Apache 2 license. 22
Update
@Dao
interface ColorDao {
...
@Update
fun update(color: Color)
...
}
Android Development with Kotlin This work is licensed under the Apache 2 license. 23
Delete
@Dao
interface ColorDao {
...
@Delete
fun delete(color: Color)
...
}
Android Development with Kotlin This work is licensed under the Apache 2 license. 24
Create a Room database
● Annotate class with @Database and include list of entities:
@Database(entities = [Color::class], version = 1)
● Declare abstract class that extends RoomDatabase:
abstract class ColorDatabase : RoomDatabase() {
○ Declare abstract method with no args that returns the DAO:
abstract fun colorDao(): ColorDao
Android Development with Kotlin This work is licensed under the Apache 2 license. 25
Example Room database
@Database(entities = [Color::class], version = 1)
abstract class ColorDatabase : RoomDatabase() {
abstract fun colorDao(): ColorDao
companion object {
@Volatile
private var INSTANCE: ColorDatabase? = null
fun getInstance(context: Context): ColorDatabase {
...
}
}
...
Android Development with Kotlin This work is licensed under the Apache 2 license. 26
Create database instance
fun getInstance(context: Context): ColorDatabase {
return INSTANCE ?: synchronized(this) {
INSTANCE ?: Room.databaseBuilder(
context.applicationContext,
ColorDatabase::class.java, "color_database"
)
.fallbackToDestructiveMigration()
.build()
.also { INSTANCE = it }
}
}
Android Development with Kotlin This work is licensed under the Apache 2 license. 27
Get and use a DAO
Get the DAO from the database:
val colorDao = ColorDatabase.getInstance(application).colorDao()
Create new Color and use DAO to insert it into database:
val newColor = Color(hex = "#6200EE", name = "purple")
colorDao.insert(newColor)
Android Development with Kotlin This work is licensed under the Apache 2 license. 28