android - 没有使用 MVVM 和 Retrofit 获取数据
问题描述
我正在尝试MVVM
在我的应用程序上使用 来获取一些数据Retrofit
,并将其显示在 a 上RecyclerView
,但是没有显示任何内容,正在记录数据,当我直接从我的活动中调用改造实例时,数据正在显示在我的RecyclerView
,不知道做错了什么。
这是我的适配器的样子
class CategoryAdapter (val context: Context):RecyclerView.Adapter<CategoryAdapter.CategoryView>(){
var category : List<Category> = listOf()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): CategoryAdapter.CategoryView {
val view = LayoutInflater.from(parent.context).inflate(R.layout.category_item, parent, false)
return CategoryView(view)
}
override fun getItemCount(): Int {
return category.size
}
override fun onBindViewHolder(holder:CategoryView, position: Int) {
val category = category[position]
holder.categoryName.text = category.name
}
class CategoryView(itemView: View, var category: Category? = null) : RecyclerView.ViewHolder(itemView){
val categoryName: TextView = itemView.findViewById(R.id.category_title)
}
}
我的ViewModel
fun loadCategories(id:Int): MutableLiveData<List<Category>>? {
var categoryList: MutableLiveData<List<Category>>? = null
RetrofitClient.makeRetrofitApi2().getCategoryProducts(id)
.enqueue(object : Callback<List<Category>> {
override fun onResponse(call: Call<List<Category>>, response: Response<List<Category>>) {
categoryList?.value = response.body()
}
override fun onFailure(call: Call<List<Category>>, t: Throwable) {
}
})
return categoryList
}
我在我的活动中如何称呼它
private fun productRecyclerView(){
recyclerView = findViewById(R.id.foodRv)
categoryAdapter = CategoryAdapter(this)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = categoryAdapter
userViewModel = ViewModelProviders.of(this).get(UserViewModel::class.java)
userViewModel!!.loadCategories(intent.getIntExtra("VENDOR_ID", 0))?.observe(this, Observer { categories ->
categoryAdapter = CategoryAdapter(this)
categoryAdapter!!.setCategories(categories)
foodRv!!.adapter = categoryAdapter
})
}
一切都已初始化。
解决方案
首先,您需要在 viewModel 中初始化 categoryList,因为它的值为 null,如下所示:
var categoryList: MutableLiveData<List<Category>>? = MutableLiveData<>()
在适配器第一次使用 0 个项目时,不会出现任何内容,在将新获取的类别设置为适配器后,您需要通知它使用 DiffUtils 重新膨胀项目或简单地notifyDataSetChanged()
推荐阅读
- ios - 在 Adobe AIR 应用程序中使用完整的 iPhone X 分辨率
- jquery - 如何使用带有变量和其他参数的 jQuery 选择器
- reactjs - Button On press 仅适用于 React Native 中按钮的某些区域
- python-3.x - Python3.6.6 argparse 用于带有参数列表的负字符串值
- amazon-s3 - Ansible Tower 是否与 aws_S3 模块兼容?
- java - 使用泛型和动态类类型返回类型转换
- python-3.x - pandas df:如果不存在则添加列,将值从dict添加到新列
- c++ - 检查枚举类是否可用的简单宏
- android - 我无法在 Android Studio 中编译 Github 代码(同步失败,出现 5 个错误)
- c# - Xunit () 中的测试异常