问题
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
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>>
}
}
回答1:
step 1:create custom autocomplete text view
example:https://spapas.github.io/2019/04/05/android-custom-filter-adapter/
step2:get data from room dp
@Query("SELECT * FROM Gender WHERE name == :name")
fun getGenderByName(name: String): List<Gender>
step3:update this data to custom autocomplete adapter
回答2:
If i understand you want to have as entries of your autocomplete text view the data that you have in the internal DB.
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 Class
`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
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) } })
}
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
DB ====> Repository ====> ViewModel ====> Activity
来源:https://stackoverflow.com/questions/59136390/autocompletetextview-with-room