Lesson 9:
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?
Collection of structured data that can be easily accessed,
searched, and organized, consisting of:
● Tables Example Database
person car
● Rows
_id _id
● Columns name make
age model
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
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
● No compile-time verification of raw SQL queries
● Need lots of boilerplate code to convert between
SQL queries data objects
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
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")
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
● 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
colors
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
Android Development with Kotlin This work is licensed under the Apache 2 license. 20
Query
Android Development with Kotlin This work is licensed under the Apache 2 license. 21
Insert
Android Development with Kotlin This work is licensed under the Apache 2 license. 22
Update
Android Development with Kotlin This work is licensed under the Apache 2 license. 23
Delete
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
Android Development with Kotlin This work is licensed under the Apache 2 license. 26
Create database instance
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
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
● Limited time to do tasks and remain responsive
● Balanced with the need to execute long-running tasks
● Control over how and where tasks are executed
Android Development with Kotlin This work is licensed under the Apache 2 license. 31
Async programming on Android
● Threading
● Callbacks
● Plus many other options
What is the recommended way?
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
● Keep your app responsive while managing long-running tasks.
● Simplify asynchronous code in your Android app.
● Write code in sequential way
● Handle exceptions with try/catch block
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
● Add suspend modifier
● Must be called by other suspend functions or coroutines
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
Android Development with Kotlin This work is licensed under the Apache 2 license. 39
Control where coroutines run
Dispatcher Description of work Examples of work
Dispatchers.Main UI and nonblocking Updating LiveData, calling
(short) tasks suspend functions
Dispatchers.IO Network and disk tasks Database, file IO
Dispatchers.Default CPU intensive Parsing JSON
Android Development with Kotlin This work is licensed under the Apache 2 license. 40
withContext
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
● launch - no result needed
● async - can return a result
Android Development with Kotlin This work is licensed under the Apache 2 license. 43
ViewModelScope
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 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
Android Development with Kotlin This work is licensed under the Apache 2 license. 49
Create and close database for each test
In DatabaseTest.kt:
Android Development with Kotlin This work is licensed under the Apache 2 license. 50
Test insert and retrieve from a database
In DatabaseTest.kt:
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
Practice what you’ve learned by
completing the pathway:
Lesson 9: App architecture
(persistence)
Android Development with Kotlin This work is licensed under the Apache 2 license. 55