带房间的AutocompleteTextView [英] AutocompleteTextView with room
问题描述
我有一个Room db,并创建了一个模型和viewModel.我想知道如何使自动完成文本视图与数据库数据和视图模型一起使用,以根据用户类型过滤客户列表
I have a Room db and have created a model and viewModel. I was wondering how to make an autocompletetextview work with the database data and the viewmodel to filter the customer list as the user types
ViewModel
ViewModel
class CustomerVM : ViewModel() {
private val customers: MutableLiveData<List<Customer>> by lazy {
loadCustomers()
}
fun getCustomers(): LiveData<List<Customer>> {
return customers
}
private fun loadCustomers() : MutableLiveData<List<Customer>> {
return DataModel.getInstance().roomDb.CustomerDao().getAllCustomers() as MutableLiveData<List<Customer>>
}
}
推荐答案
如果我理解您希望将其作为自动完成文本的条目,请查看内部数据库中的数据.
If i understand you want to have as entries of your autocomplete text view the data that you have in the internal DB.
为此,我创建了具有allStudentsData的自定义ViewModel,并存储了来自活动的监听
To do that i create my custom ViewModel with allStudentsData, repository an listen from activity
-
存储库类 直接从数据库监听的存储库
Repository Class A repository that is listening directly from DB
val allStudents: LiveData<List<Student>> = studentDao.getAll()
ViewModel类
ViewModel Class
`priv val all学生:LiveData> 初始化{
`private val allStudents: LiveData> init {
val studentsDao = AppDatabase.getDatabase(application,viewModelScope).studentsDao()
studentRepository = StudentRepository(studentsDao)
allStudents = studentRepository.allStudents
}`
-
活动分类
Activity Class
private lateinit var studentViewModel:StudentViewModel
private lateinit var studentViewModel: StudentViewModel
公共重写乐趣onCreate(savedInstanceState:Bundle?){
public override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
studentViewModel = ViewModelProvider(this).get(StudentViewModel::class.java)
studentViewModel.allStudents.observe(this, Observer { students ->
// Update the cached copy of the students in the adapter.
students?.let {
val arr = mutableListOf<String>()
for (value in it) {
arr.add(value.name)
}
val adapter: ArrayAdapter<String> =
ArrayAdapter(this, android.R.layout.select_dialog_item, arr)
names.setAdapter(adapter)
}
})
}
在活动中,我们有一个viewModel变量,用于观察在DB中插入新记录时更改的数据. 当我们有新数据Observer {}被调用时,因此使用新的学生列表,我们创建了一个可变列表,我们添加了所有学生,并设置了适配器
In the activity we have a viewModel variable that observe the data that is change when new record is insert in DB. When we have new data Observer {} is called, so with the new list of students we create a mutable list, we add all students and we set the adapter
这样做,当数据库中的数据更改时
By doing this, when data change in DB
数据库 ====> 存储库 ====> ViewModel ====> 活动
DB ====> Repository ====> ViewModel ====> Activity
这篇关于带房间的AutocompleteTextView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!