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.