0
0
Android Kotlinmobile~20 mins

Room database setup in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: User List
This screen shows a list of users stored in a local Room database. Users can be added and retrieved from the database.
Target UI
---------------------
| User List         |
|-------------------|
| + Add User        |
|                   |
| [List of users]   |
|                   |
---------------------
Set up Room database with an Entity called User with fields: id (auto-generated), name (String), and age (Int).
Create a DAO interface with methods to insert a user and get all users.
Create the Room database class.
In the main activity, display the list of users from the database.
Add a FloatingActionButton to add a new user with a fixed name and age for simplicity.
Starter Code
Android Kotlin
package com.example.roomsetup

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContent {
            // TODO: Add UI and database code here
        }
    }
}

// TODO: Define User entity

// TODO: Define UserDao interface

// TODO: Define AppDatabase abstract class
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Solution
Android Kotlin
package com.example.roomsetup

import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.lifecycle.lifecycleScope
import androidx.room.*
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

@Entity
data class User(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val name: String,
    val age: Int
)

@Dao
interface UserDao {
    @Insert
    suspend fun insert(user: User)

    @Query("SELECT * FROM User")
    suspend fun getAll(): List<User>
}

@Database(entities = [User::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun userDao(): UserDao
}

class MainActivity : ComponentActivity() {
    private lateinit var db: AppDatabase

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        db = Room.databaseBuilder(
            applicationContext,
            AppDatabase::class.java, "user-database"
        ).build()

        setContent {
            var users by remember { mutableStateOf<List<User>>(emptyList()) }

            LaunchedEffect(Unit) {
                users = withContext(Dispatchers.IO) { db.userDao().getAll() }
            }

            Scaffold(
                floatingActionButton = {
                    FloatingActionButton(onClick = {
                        lifecycleScope.launch {
                            withContext(Dispatchers.IO) {
                                db.userDao().insert(User(name = "John Doe", age = 30))
                            }
                            users = withContext(Dispatchers.IO) { db.userDao().getAll() }
                        }
                    }) {
                        Text("+")
                    }
                }
            ) { paddingValues ->
                Column(modifier = androidx.compose.ui.Modifier.padding(paddingValues)) {
                    Text("User List", style = MaterialTheme.typography.headlineMedium, modifier = androidx.compose.ui.Modifier.padding(16.dp))
                    LazyColumn {
                        items(users) { user ->
                            Text(text = "${user.name}, Age: ${user.age}", modifier = androidx.compose.ui.Modifier.padding(8.dp))
                        }
                    }
                }
            }
        }
    }
}

We defined a User data class as an Entity with an auto-generated primary key. The UserDao interface has methods to insert a user and get all users. The AppDatabase class extends RoomDatabase and provides access to the DAO.

In MainActivity, we build the database instance. We use Compose to display the list of users in a LazyColumn. A floating action button inserts a new user with fixed data when clicked, then reloads the list from the database.

This setup shows how to connect Room database with UI and perform basic insert and query operations.

Final Result
Completed Screen
---------------------
| User List         |
|-------------------|
| + Add User        |
|                   |
| John Doe, Age: 30 |
| John Doe, Age: 30 |
| ...               |
---------------------
Tapping the '+' button adds a new user named 'John Doe' aged 30 to the list.
The list updates immediately to show all users stored in the database.
Stretch Goal
Add a dialog to input user name and age instead of fixed values.
💡 Hint
Use Compose AlertDialog with TextFields to get user input, then insert the new user with entered data.