0
0
Android Kotlinmobile~20 mins

Entity, DAO, Database classes in Android Kotlin - Mini App: Build & Ship

Choose your learning style9 modes available
Build: Simple Note Storage
This screen allows users to save and view simple text notes using Room database with Entity, DAO, and Database classes.
Target UI
-------------------------
| Simple Note Storage    |
-------------------------
| [Enter note here]      |
| [Save Note Button]     |
|-----------------------|
| Saved Notes:           |
| - Note 1               |
| - Note 2               |
| ...                    |
-------------------------
Create a Note entity class with id (auto-generated) and text fields.
Create a NoteDao interface with insert and getAllNotes functions.
Create a RoomDatabase class named AppDatabase that provides NoteDao.
Build a simple UI with an EditText to enter note text and a Button to save the note.
Display the list of saved notes below the input.
Use Kotlin coroutines to perform database operations off the main thread.
Starter Code
Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch

class MainActivity : ComponentActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // TODO: Initialize database
        setContent {
            MaterialTheme {
                NoteScreen()
            }
        }
    }
}

@Composable
fun NoteScreen() {
    var noteText by remember { mutableStateOf("") }
    var notes by remember { mutableStateOf(listOf<String>()) }

    // TODO: Add UI and database interaction

    Column {
        OutlinedTextField(
            value = noteText,
            onValueChange = { noteText = it },
            label = { Text("Enter note") },
            modifier = androidx.compose.ui.Modifier.fillMaxWidth()
        )
        Button(onClick = { /* TODO: Save note */ }) {
            Text("Save Note")
        }
        Text("Saved Notes:")
        LazyColumn {
            items(notes) { note ->
                Text(note)
            }
        }
    }
}
Task 1
Task 2
Task 3
Task 4
Task 5
Task 6
Solution
Android Kotlin
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.Button
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.MaterialTheme
import androidx.compose.runtime.*
import androidx.room.*
import androidx.lifecycle.lifecycleScope
import kotlinx.coroutines.launch

@Entity(tableName = "notes")
data class Note(
    @PrimaryKey(autoGenerate = true) val id: Int = 0,
    val text: String
)

@Dao
interface NoteDao {
    @Insert
    suspend fun insert(note: Note)

    @Query("SELECT * FROM notes")
    suspend fun getAllNotes(): List<Note>
}

@Database(entities = [Note::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
    abstract fun noteDao(): NoteDao
}

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

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        db = Room.databaseBuilder(
            applicationContext,
            AppDatabase::class.java,
            "notes-db"
        ).build()

        setContent {
            MaterialTheme {
                NoteScreen(db.noteDao())
            }
        }
    }
}

@Composable
fun NoteScreen(noteDao: NoteDao) {
    var noteText by remember { mutableStateOf("") }
    var notes by remember { mutableStateOf(listOf<Note>()) }

    LaunchedEffect(Unit) {
        notes = noteDao.getAllNotes()
    }

    Column {
        OutlinedTextField(
            value = noteText,
            onValueChange = { noteText = it },
            label = { Text("Enter note") },
            modifier = androidx.compose.ui.Modifier.fillMaxWidth()
        )
        Button(onClick = {
            if (noteText.isNotBlank()) {
                // Save note in coroutine
                androidx.compose.runtime.LaunchedEffect(noteText) {
                    noteDao.insert(Note(text = noteText))
                    notes = noteDao.getAllNotes()
                    noteText = ""
                }
            }
        }) {
            Text("Save Note")
        }
        Text("Saved Notes:")
        LazyColumn {
            items(notes) { note ->
                Text(note.text)
            }
        }
    }
}

We created a Note entity with an auto-generated id and a text field to store the note content. The NoteDao interface defines two suspend functions: insert to add a note and getAllNotes to retrieve all saved notes.

The AppDatabase class extends RoomDatabase and provides access to the DAO.

In MainActivity, we initialize the Room database and pass the DAO to the composable NoteScreen.

The UI has an OutlinedTextField for input, a Button to save the note, and a LazyColumn to display saved notes. We use Kotlin coroutines with LaunchedEffect to perform database operations off the main thread and update the UI state accordingly.

Final Result
Completed Screen
-------------------------
| Simple Note Storage    |
-------------------------
| [Enter note here]      |
| [Save Note Button]     |
|-----------------------|
| Saved Notes:           |
| - Buy groceries        |
| - Call mom             |
| - Read book            |
-------------------------
User types a note in the text field.
User taps 'Save Note' button.
Note is saved to the database asynchronously.
Saved notes list updates immediately to show the new note.
Stretch Goal
Add a pull-to-refresh gesture to reload the notes list from the database.
💡 Hint
Use SwipeRefresh from accompanist library or Compose's built-in pull refresh to trigger reloading notes.