I built a very simple ROOM in Jetpack Compose, not using ViewModel for study. The app stops. The codes are as follows. Thanks in advance any suggestions.
First, I built the ROOM database as follows, following the standard method:
@Entity(tableName = "notes")
data class Note(
@PrimaryKey(autoGenerate = true)
val id: Int,
val title: String,
val content: String
)
@Dao
interface NoteDao {
@Query("SELECT * FROM notes")
fun getAllNotes(): List<Note>
@Insert
fun insert(note: Note): Long
}
@Database(entities = [Note::class], version = 1)
abstract class AppDatabase : RoomDatabase() {
abstract fun noteDao(): NoteDao
}
Then, I used this ROOMdatabase in MainActivity:
class MainActivity : ComponentActivity() {
private lateinit var db: AppDatabase
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val db = Room.databaseBuilder(
applicationContext,
AppDatabase::class.java, "note-database"
).build()
...
NotesApp(db.noteDao())
...
}
Where NoteApp is defined as
@Composable
fun NotesApp(noteDao: NoteDao) {
val notes = remember { mutableStateListOf<Note>() }
val title = remember { mutableStateOf("") }
val content = remember { mutableStateOf("") }
val coroutineScope = rememberCoroutineScope()
LaunchedEffect(Unit) {
coroutineScope.launch {
notes.clear()
notes.addAll(noteDao.getAllNotes())
}
}
Column(modifier = Modifier.fillMaxSize()) {
TextField(
value = title.value,
onValueChange = { title.value = it },
label = { Text("Title") },
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
TextField(
value = content.value,
onValueChange = { content.value = it },
label = { Text("Content") },
modifier = Modifier
.fillMaxWidth()
.padding(16.dp)
)
Button(
onClick = {
val newNote = Note(0, title.value, content.value)
coroutineScope.launch {
noteDao.insert(newNote)
notes.clear()
notes.addAll(noteDao.getAllNotes())
}
},
modifier = Modifier.padding(16.dp)
) {
Text("Add Note")
}
LazyColumn(modifier = Modifier.fillMaxSize()) {
items(notes.size) { index ->
NoteItem(notes[index])
}
}
}
}
@Composable
fun NoteItem(note: Note) {
Card(
modifier = Modifier
.fillMaxWidth()
.padding(8.dp)
) {
Column(modifier = Modifier.padding(16.dp)) {
Text(text = note.title, style = MaterialTheme.typography.bodyMedium)
Text(text = note.content, style = MaterialTheme.typography.bodySmall)
}
}
}