Android recyclerview 和 fragment :将我的数据提取到我的回收器视图中

Android recyclerview and fragment : put my data fetch into my recycler view

自 1 周以来我一直坚持这个问题,我不明白为什么我的数据提取没有显示在我的 cardAdaptater 中。我可以看到它们获取得很好,但我无法在片段中访问它们

这是我的 HomePageFragment,其中应显示数据

class HomePage {
    class HomeFragment : Fragment(), HeaderScrollBarAdapter.ItemClickListener {

        private var cardAdapter: HomeCardItemAdapter? = null
        private val url = "https://kolibrii-prod.herokuapp.com/tutorial"
        private var listTuto = ArrayList<Model.Tuto>()

        override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
            inflater.inflate(R.layout.fragment_home, container, false)



        override fun onViewCreated(view: View, savedInstanceState: Bundle?) {

            super.onViewCreated(view, savedInstanceState)
            getData()         



            // Set up card recycler view
            val cardRecyclerView = view.findViewById<RecyclerView>(R.id.menuheaderscrollbar2)
            val verticalLayoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
            cardRecyclerView.layoutManager = verticalLayoutManager
            cardRecyclerView.adapter = cardAdapter
            Log.d("tutorender",listTuto.toString())
        }

        // Function to fetch Tutorial data
        private fun getData() {

            val jsonArrayRequest = JsonArrayRequest(url,
                Response.Listener<JSONArray> { response ->
                    for (i in 0 until response.length()) {
                        try {
                            val jsonObject = response.getJSONObject(i)
                            val jsonTitle = jsonObject.getString("title")
                            val jsonDuration = jsonObject.getString("duration")
                            val jsonPrice = jsonObject.getString("price")
                            val jsonLevel = "Facile"
                            val jsonImg = (R.drawable.testons)
                            val jsonId = jsonObject.getInt("id")
                            val tutoEntrie = Model.Tuto(jsonTitle,jsonDuration,jsonPrice,jsonLevel, jsonImg, jsonId)
                            listTuto.add(tutoEntrie)
                        }
                        catch (e: JSONException) {
                            e.printStackTrace()
                        }

                    }

                    cardAdapter?.notifyDataSetChanged()
                    Log.d("tuto", listTuto.toString())
                }, Response.ErrorListener { Log.e("Volley", "Volley error on tutorial") })
            val requestQueue = Volley.newRequestQueue(activity)
            requestQueue.add(jsonArrayRequest)
        }
    }
}

这是我的 cardAdapter.kit :

class HomeCardItemAdapter // data is passed into the constructor
internal constructor(
    context: FragmentActivity?,
    private val tutos: ArrayList<Model.Tuto>
   //private val mCatePicture: List<Int>
)
    : RecyclerView.Adapter<HomeCardItemAdapter.ViewHolder>() {
    private val mInflater: LayoutInflater = LayoutInflater.from(context)
    private var mClickListener: ItemClickListener? = null


    // inflates the row layout from xml when needed
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view = mInflater.inflate(R.layout.feed_card_items, parent, false)
        return ViewHolder(view)
    }

    // binds the data to the view and textview in each row
    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val currentTuto = tutos.get(position)
     //   val catePicture= mCatePicture[position]
        holder.titleTextView.text = currentTuto.title
        holder.timeTextView.text = currentTuto.duration
        holder.priceTextView.text = currentTuto.price
       holder.levelTextView.text = currentTuto.level
        //holder.categoryImageView.setImageResource(catePicture)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            holder.cardImageView.clipToOutline = true
        }
    }

    // total number of rows
    override fun getItemCount(): Int {
                return tutos.size
        }

    // stores and recycles views as they are scrolled off screen
    inner class ViewHolder internal constructor(itemView: View) : RecyclerView.ViewHolder(itemView),
        View.OnClickListener {
        internal var cardImageView: ImageView = itemView.findViewById(R.id.card_img_bg)
        internal var titleTextView: TextView = itemView.findViewById(R.id.card_title)
        internal var priceTextView: TextView = itemView.findViewById(R.id.card_price)
        internal var timeTextView: TextView = itemView.findViewById(R.id.card_time)
        internal var levelTextView: TextView = itemView.findViewById(R.id.card_level)
        internal var categoryImageView: ImageView = itemView.findViewById(R.id.card_theme_icon)


}

提前感谢可以帮助我的人

您永远不会初始化适配器,它始终为 null,并且由于安全运算符 (?),这些调用从未真正被调用。

// Function to fetch Tutorial data
private fun getData() {
   val jsonArrayRequest = JsonArrayRequest(url,
   Response.Listener<JSONArray> { response ->
   for (i in 0 until response.length()) {
      try {
         val jsonObject = response.getJSONObject(i)
         val jsonTitle = jsonObject.getString("title")
         val jsonDuration = jsonObject.getString("duration")
         val jsonPrice = jsonObject.getString("price")
         val jsonLevel = "Facile"
         val jsonImg = (R.drawable.testons)
         val jsonId = jsonObject.getInt("id")
         val tutoEntrie = Model.Tuto(jsonTitle,jsonDuration,jsonPrice,jsonLevel, jsonImg, jsonId)
         listTuto.add(tutoEntrie)
      } catch (e: JSONException) {
         e.printStackTrace()
      }

    }

    // THIS HERE IS NEVER ACTUALLY CALLED AS THE ADAPTER IS ALWAYS NULL
    cardAdapter?.notifyDataSetChanged()

    Log.d("tuto", listTuto.toString())
    }, Response.ErrorListener { Log.e("Volley", "Volley error on tutorial") })
        val requestQueue = Volley.newRequestQueue(activity)
        requestQueue.add(jsonArrayRequest)
    } 
}

在 notifyDataSetChanged 之前添加这个

cardAdapter = HomeCardItemAdapter(this, listTuto)
// attach adapter
findViewById<RecyclerView>(R.id.menuheaderscrollbar2).adapter = cardAdapter
cardAdapter?.notifyDataSetChanged() // this might not be necessary

编辑:添加了进一步的解释:

您调用 getData() 是在配置您的 recyclerview 和附加适配器之前。因此,您应该按如下方式修改 onViewCreated()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
     super.onViewCreated(view, savedInstanceState)

     // Set up card recycler view
     val cardRecyclerView = view.findViewById<RecyclerView>(R.id.menuheaderscrollbar2)
     val verticalLayoutManager = LinearLayoutManager(activity, LinearLayoutManager.VERTICAL, false)
     cardRecyclerView.layoutManager = verticalLayoutManager

     // now that recyclerview is ready
     getData()         
}