【问题标题】:How to use SearchView with LiveData and ViewModel in Room如何在 Room 中将 SearchView 与 LiveData 和 ViewModel 一起使用
【发布时间】:2020-01-14 15:33:33
【问题描述】:

我想使用 SearchView 搜索房间数据库中的某些元素,但我遇到了问题,因为我无法在 RecyclerViewAdapter 中使用 getFilter,因为我有 ViewModel,也许谁知道如何将所有这些元素组合到一个项目中。
我搜索一种使用 Transormations.switchMap 的方法。但我无法连接它们。

ProductViewModel

class ProductViewModel(application: Application) : AndroidViewModel(application) {
    private val repository: ProductRepository

    val allProducts: LiveData<List<ProductEntity>>
    private val searchStringLiveData = MutableLiveData<String>()

    init {
        val productDao = ProductsDB.getDatabase(application, viewModelScope).productDao()
        repository = ProductRepository(productDao)
        allProducts = repository.allProducts
        searchStringLiveData.value = ""
    }

    fun insert(productEntity: ProductEntity) = viewModelScope.launch {
        repository.insert(productEntity)
    }


    val products = Transformations.switchMap(searchStringLiveData) { string ->
        repository.getAllListByName(string)

    }

    fun searchNameChanged(name: String) {
        searchStringLiveData.value = name
    }



}

ProductDao

interface ProductDao {

    @Insert(onConflict = OnConflictStrategy.IGNORE)
    suspend fun insertProduct(productEntity: ProductEntity)

    @Query("SELECT * from products")
    fun getListAllProducts(): LiveData<List<ProductEntity>>


    @Query("DELETE FROM products")
    suspend fun deleteAll()

    @Query("SELECT * FROM products where product_name_ent LIKE :name or LOWER(product_name_ent) like LOWER(:name)")
    fun  getListAllByName(name: String):LiveData<List<String>>

}

【问题讨论】:

    标签: android kotlin viewmodel searchview


    【解决方案1】:

    ProductDao

    @Query("SELECT * FROM products where product_name_ent LIKE :name or LOWER(product_name_ent) like LOWER(:name)")
                fun  getListAllByName(name: String):LiveData<List<ProductEntity>>
    

    您的 dao 中的此方法应返回 LiveData&lt;List&lt;ProductEntity&gt;&gt; 而不是 LiveData&lt;List&lt;String&gt;&gt;,因为此查询从实体中选择 所有内容 (*) 而 不是 特定列。

    类似于 (@Query("SELECT * from products") fun getListAllProducts():LiveData&lt;List&lt;ProductEntity&gt;&gt;)

    ProductViewModel

        class ProductViewModel(application: Application) : AndroidViewModel(application) {
            private val repository: ProductRepository
            init {
                val productDao = ProductsDB.getDatabase(
                    application,
                    viewModelScope
                ).productDao()
                repository = ProductRepository(productDao)
            }
    
    
            private val searchStringLiveData = MutableLiveData<String>("") //we can add initial value directly in the constructor
            val allProducts: LiveData<List<ProductEntity>>=Transformations.switchMap(searchStringLiveData)
            {
                string->
                if (TextUtils.isEmpty(string)) {
                    repository.allProducts()
                } else {
                    repository.allProductsByName(string)
                }
            }
    
    
            fun insert(productEntity: ProductEntity) = viewModelScope.launch {
                repository.insert(productEntity)
            }
    
            fun searchNameChanged(name: String) {
                searchStringLiveData.value = name
            }
    
    
        }
    

    存储库

    ...使用您拥有的其他方法,添加以下内容:

    fun allProducts():LiveData<List<ProductEntity>>=productDao.getListAllProducts()
    fun allProductsByNames(name:String):LiveData<List<ProductEntity>>=productDao.getListAllByName(name)
    

    在你的 Activity 或 Fragment 中你有 recyclerview 适配器的地方

    onCreate() 内部(如果是活动)

    viewModel.allProducts.observe(this,Observer{products->
    //populate your recyclerview here
    })
    

    onActivityCreated(if it is a fragment)
           viewModel.allProducts.observe(viewLifecycleOwner,Observer{products->
        //populate your recyclerview here
        })
    

    现在为 searchView 设置一个监听器,每次用户提交查询时,调用viewModel.searchNameChanged(// pass the new value)

    希望对你有帮助

    问候,

    【讨论】:

      猜你喜欢
      • 2018-11-29
      • 2020-03-17
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      • 2019-06-06
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多