数据库更改时更新适配器

问题描述 投票:0回答:1

我正在制作一个简单的应用程序,其主要活动带有

RecyclerView
。主要活动从
SQLiteOpenHelper
类获取注释并将注释设置到适配器中。

还有其他活动可以创建新笔记并将其记录在数据库中。没有“保存”按钮,因此保存工作是在

onStop()
方法中完成的,如下所示:

    override fun onStop() {
        super.onStop()
        val textInputEditTitle : TextInputEditText = this.findViewById(R.id.textInputNoteTitle)
        val textInputEditText : TextInputEditText = this.findViewById(R.id.textInputNoteText)
        note = Note(textInputEditTitle.text.toString(), textInputEditText.text.toString())
        val dbHandler = DbHandler(this)
        dbHandler.insertNote(note)
        dbHandler.close()
    }

问题是当返回主活动时,RecyclerView 不显示新注释。

我在主要活动中尝试过这个:

    override fun onResume(){
        super.onResume()
        notes = dbHandler.getNotes()
        for(note in notes) Log.d(TAG, note.toString())
        noteAdapter.setData(notes)
        noteAdapter.notifyDataSetChanged()
    }

但是日志只显示旧的笔记,而不显示新的笔记。

理想情况下,我想通过

SQLiteOpenHelper
类中的插入更新和删除方法调用更新 noteApater 的数据,因此每次更新数据库时,适配器也会更新。我不能这样做,因为第二个活动必须知道适配器才能初始化数据库。

有什么建议吗?

android sqlite kotlin android-recyclerview
1个回答
0
投票

您可以使用 Room DB 并从 DB 获取观察者,然后在您的活动中观察它 如果您是 android Room 的新手,您可以使用这个 android 官方教程来学习 - https://developer.android.com/codelabs/android-room-with-a-view-kotlin#0

© www.soinside.com 2019 - 2024. All rights reserved.