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

时间:2019-05-28 19:46:43

标签: android android-fragments kotlin android-recyclerview android-volley

自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)


}

预先感谢可以帮助我的人

1 个答案:

答案 0 :(得分:0)

您永远不会初始化适配器,适配器始终为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()         
}