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