android 无法在从viewModel获取的recyclerview中显示项目

fnvucqvd  于 2023-02-02  发布在  Android
关注(0)|答案(1)|浏览(145)

我有一个editText和一个按钮。当我点击按钮时,edittext中的数据被插入到数据库中。在保存活动中,我有recyclerView,它将显示从viewModel中获得的项目。我已经放置了观察器来观察数据,但它没有显示recuclerView中的任何项目。

class MainActivity : AppCompatActivity(), NoteAdapter.OnItemClicked {

    private lateinit var recyclerView: RecyclerView
    private lateinit var btnAdd: Button
    private lateinit var etNote: EditText
    lateinit var viewModel: MyViewModel

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        recyclerView = findViewById(R.id.recyclerView)
        btnAdd = findViewById(R.id.btn_add)
        etNote = findViewById(R.id.et_note)

        val mAdapter = NoteAdapter(this)

        recyclerView.apply {
            adapter = mAdapter
            layoutManager = LinearLayoutManager(this@MainActivity)
        }

        viewModel = ViewModelProvider(this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application))[MyViewModel::class.java]

        viewModel.allNotes.observe(this, Observer {note->
            note?.let {
                mAdapter.submitList(it)
            }
        })

        btnAdd.setOnClickListener {
            addNote()
        }
    }

    override fun onClick(note: Notes) {
        viewModel.delete(note)
    }

    private fun addNote(){
        val note: String = etNote.text.toString()

        if(note.isNotEmpty()) {
            viewModel.insert(Notes(note))
            Toast.makeText(this, "$note inserted", Toast.LENGTH_SHORT).show()
        }
    }
}

适配器类别

class NoteAdapter(private val clickListener: OnItemClicked)
    : ListAdapter<Notes, NoteAdapter.MyViewHolder>(NoteComparator()) {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.note_item, parent, false)
        val viewHolder = MyViewHolder(view)

        viewHolder.ivDelete.setOnClickListener{
            clickListener.onClick(getItem(viewHolder.adapterPosition))
        }

        return viewHolder
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        val currentNote = getItem(position)
        holder.apply {
            tvNoteItem.text = currentNote.note
        }
    }

    interface OnItemClicked{
        fun onClick(note: Notes)
    }

    class MyViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        val tvNoteItem: TextView = itemView.findViewById(R.id.tv_note)
        val ivDelete: ImageView = itemView.findViewById(R.id.iv_delete)
    }
    
    class NoteComparator : DiffUtil.ItemCallback<Notes>(){
        override fun areItemsTheSame(oldItem: Notes, newItem: Notes): Boolean {
            return oldItem == newItem
        }

        override fun areContentsTheSame(oldItem: Notes, newItem: Notes): Boolean {
            return oldItem == newItem
        }
    }
}

视图模型类

class MyViewModel(application: Application) : AndroidViewModel(application) {

    private val repository: NotesRepository
    val allNotes : LiveData<List<Notes>>

    init {
        val dao = NoteDatabase.getDatabase(application).noteDao()
        repository = NotesRepository(dao)
        allNotes = repository.noteList
    }

    fun delete(note: Notes) = viewModelScope.launch(Dispatchers.IO) {
        repository.delete(note)
    }

    fun insert(note: Notes) = viewModelScope.launch(Dispatchers.IO) {
        repository.insert(note)
    }
}
72qzrwbm

72qzrwbm1#

嘿,迪维扬什,
分析你的代码,我认为问题出在你的ViewModel中。你正在尝试更改属性allNotes,它是一个LiveData。你需要可变的实时数据,所以把它声明为private,因为我们不能公开可变属性。你的allNotes属性将接收来自这个可变属性的更改,如下所示:

class MyViewModel: ViewModel() {

    private val _allNotes = MutableLiveData<List<Notes>>(emptyList())
    val allNotes: LiveData<List<Notes>>
        get() = _allNotes

}

然后,更新可变实时数据:

class MyViewModel: ViewModel() {
    // ...
    init {
        val dao = NoteDatabase.getDatabase(application).noteDao()
        repository = NotesRepository(dao)
        _allNotes.value = repository.noteList
    }
    
}

相关问题