Lesson 9 App Architecture (Persistence)
Lesson 9 App Architecture (Persistence)
App architecture
(persistence)
Android Development with Kotlin v1.0 This work is licensed under the Apache 2 license. 1
About this lesson
Lesson 9: App architecture (persistence)
● Storing data
● Room persistence library
● Asynchronous programming
● Coroutines
● Testing databases
● Summary
Android Development with Kotlin This work is licensed under the Apache 2 license. 2
Storing data
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
● Shared storage (files to be shared with other apps)
● Preferences
● Databases
Android Development with Kotlin This work is licensed under the Apache 2 license. 4
What is a database?
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.
Android Development with Kotlin This work is licensed under the Apache 2 license. 6
SQLite in Android
Store data
Your app
SQLite database
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
Android Development with Kotlin This work is licensed under the Apache 2 license. 9
Room persistence library
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"
// Test helpers
testImplementation "androidx.room:room-testing:$room_version"
}
Android Development with Kotlin This work is licensed under the Apache 2 license. 11
Room
Color("#FF0000", "red")
Room
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
● Entity Color
● DAO ColorDao
● Database ColorDatabase
Android Development with Kotlin This work is licensed under the Apache 2 license. 14
Color class
Android Development with Kotlin This work is licensed under the Apache 2 license. 15
Annotations
@Entity(tableName = "colors")
● Can autogenerate code for you
Android Development with Kotlin This work is licensed under the Apache 2 license. 16
Entity
Android Development with Kotlin This work is licensed under the Apache 2 license. 17
Example entity
@Entity(tableName = "colors")
colors
data class Color {
_id
@PrimaryKey(autoGenerate = true) val _id: Int, hex_color
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)
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 {
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
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
Android Development with Kotlin This work is licensed under the Apache 2 license. 28
Asynchronous
programming
Android Development with Kotlin This work is licensed under the Apache 2 license. 29
Long-running tasks
● Download information
● Sync with a server
● Write to a file
● Heavy computation
● Read from, or write to, a database
Android Development with Kotlin This work is licensed under the Apache 2 license. 30
Need for async programming
Android Development with Kotlin This work is licensed under the Apache 2 license. 31
Async programming on Android
● Threading
● Callbacks
● Plus many other options
Android Development with Kotlin This work is licensed under the Apache 2 license. 32
Coroutines
Android Development with Kotlin This work is licensed under the Apache 2 license. 33
Coroutines
Android Development with Kotlin This work is licensed under the Apache 2 license. 34
Benefits of coroutines
● Lightweight
● Fewer memory leaks
● Built-in cancellation support
● Jetpack integration
Android Development with Kotlin This work is licensed under the Apache 2 license. 35
Suspend functions
Android Development with Kotlin This work is licensed under the Apache 2 license. 36
Suspend and resume
● suspend
Pauses execution of current coroutine and saves local variables
● resume
Automatically loads saved state and continues execution from
the point the code was suspended
Android Development with Kotlin This work is licensed under the Apache 2 license. 37
Example
Android Development with Kotlin This work is licensed under the Apache 2 license. 38
Add suspend modifier to DAO methods
@Dao
interface ColorDao {
@Query("SELECT * FROM colors")
suspend fun getAll(): Array<Color>
@Insert
suspend fun insert(vararg color: Color)
@Update
suspend fun update(color: Color)
@Delete
suspend fun delete(color: Color)
Android Development with Kotlin This work is licensed under the Apache 2 license. 39
Control where coroutines run
Android Development with Kotlin This work is licensed under the Apache 2 license. 40
withContext
suspend fun get(url: String) {
// Start on Dispatchers.Main
withContext(Dispatchers.IO) {
// Switches to Dispatchers.IO
// Perform blocking network IO here
}
// Returns to Dispatchers.Main
}
Android Development with Kotlin This work is licensed under the Apache 2 license. 41
CoroutineScope
Coroutines must run in a CoroutineScope:
● Keeps track of all coroutines started in it (even suspended ones)
● Provides a way to cancel coroutines in a scope
● Provides a bridge between regular functions and coroutines
Examples: GlobalScope
ViewModel has viewModelScope
Lifecycle has lifecycleScope
Android Development with Kotlin This work is licensed under the Apache 2 license. 42
Start new coroutines
Android Development with Kotlin This work is licensed under the Apache 2 license. 43
ViewModelScope
init {
viewModelScope.launch {
// Coroutine that will be canceled
// when the ViewModel is cleared
}
}
...
Android Development with Kotlin This work is licensed under the Apache 2 license. 44
Example viewModelScope
...
Android Development with Kotlin This work is licensed under the Apache 2 license. 45
Testing databases
Android Development with Kotlin This work is licensed under the Apache 2 license. 46
Add Gradle dependencies
android {
defaultConfig {
...
testInstrumentationRunner "androidx.test.runner
.AndroidJUnitRunner"
testInstrumentationRunnerArguments clearPackageData: 'true'
}
}
dependencies {
testImplementation 'junit:junit:4.12'
androidTestImplementation 'androidx.test.ext:junit:1.1.0'
androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'
}
Android Development with Kotlin This work is licensed under the Apache 2 license. 47
Testing Android code
● @RunWith(AndroidJUnit4::class)
● @Before
● @After
● @Test
Android Development with Kotlin This work is licensed under the Apache 2 license. 48
Create test class
@RunWith(AndroidJUnit4::class)
class DatabaseTest {
...
Android Development with Kotlin This work is licensed under the Apache 2 license. 49
Create and close database for each test
In DatabaseTest.kt:
@Before
fun createDb() {
val context: Context = ApplicationProvider.getApplicationContext()
db = Room.inMemoryDatabaseBuilder(context, ColorDatabase::class.java)
.allowMainThreadQueries()
.build()
colorDao = db.colorDao()
}
@After
@Throws(IOException::class)
fun closeDb() = db.close()
Android Development with Kotlin This work is licensed under the Apache 2 license. 50
Test insert and retrieve from a database
In DatabaseTest.kt:
@Test
@Throws(Exception::class)
fun insertAndRetrieve() {
colorDao.insert(red, green, blue)
val colors = colorDao.getAll()
assert(colors.size == 3)
}
Android Development with Kotlin This work is licensed under the Apache 2 license. 51
Summary
Android Development with Kotlin This work is licensed under the Apache 2 license. 52
Summary
In Lesson 9, you learned how to:
● Set up and configure a database using the Room library
● Use coroutines for asynchronous programming
● Use coroutines with Room
● Test a database
Android Development with Kotlin This work is licensed under the Apache 2 license. 53
Learn more
● 7 Pro-tips for Room
● Room Persistence Library
● SQLite Home Page
● Save data using SQLite
● Coroutines Guide
● Dispatchers - kotlinx-coroutines-core
● Coroutines on Android (part I): Getting the background
● Coroutines on Android (part II): Getting started
● Easy Coroutines in Android: viewModelScope
● Kotlin Coroutines 101
Android Development with Kotlin This work is licensed under the Apache 2 license. 54
Pathway
Android Development with Kotlin This work is licensed under the Apache 2 license. 55