首页 > 解决方案 > 没有使用 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

    })
}

一切都已初始化。

标签: androidkotlinmvvmretrofit2

解决方案


首先,您需要在 viewModel 中初始化 categoryList,因为它的值为 null,如下所示:

 var categoryList: MutableLiveData<List<Category>>? = MutableLiveData<>()

在适配器第一次使用 0 个项目时,不会出现任何内容,在将新获取的类别设置为适配器后,您需要通知它使用 DiffUtils 重新膨胀项目或简单地notifyDataSetChanged()


推荐阅读