AutocompleteTextView with room

点点圈 提交于 2020-01-25 10:18:05

问题


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

  1. Repository Class A repository that is listening directly from DB

    val allStudents: LiveData<List<Student>> = studentDao.getAll()

  2. ViewModel Class

`private val allStudents: LiveData> init {

    val studentsDao = AppDatabase.getDatabase(application,viewModelScope).studentsDao()
    studentRepository = StudentRepository(studentsDao)
    allStudents = studentRepository.allStudents
}`
  1. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!