android 在Jetpack Compose中构建没有ViewModel的ROOM存在问题

pdkcd3nj  于 2023-05-12  发布在  Android
关注(0)|答案(1)|浏览(187)

我在Jetpack Compose中构建了一个非常简单的ROOM,没有使用ViewModel进行学习。app停止了。代码如下。提前感谢任何建议。
首先,我按照以下标准方法构建了ROOM数据库:

@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
}

然后,我在MainActivity中使用了这个ROOM数据库:

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())
    ...
}

其中NoteApp定义为

@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)
    }
}
}
des4xlb0

des4xlb01#

我假设你得到了使用未初始化变量db的错误;问题是,在**onCreate()**中,您声明了一个新的db,而没有初始化Activity中的db
因此,我怀疑你在其他地方使用了未初始化的变量,所以它产生了错误,或者请与我们分享你得到的错误!

相关问题