Обзор и фрагмент Android-утилит - PullRequest
1 голос
/ 28 мая 2019

Я застрял с этим с 1 недели, и я не могу понять, почему мои данные не отображаются в моем адаптере карты. Я вижу, что они хорошо загружены, но я не могу получить к ним доступ после фрагмента

Вот мой 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)
        }
    }
}

Вот моя карта Adapter.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 голосов
/ 28 мая 2019

Вы никогда не инициализируете адаптер, он всегда нулевой, и из-за оператора safe (?) Эти вызовы никогда не выполняются.

// 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 () перед настройкой вашего реселлера и подключением адаптера,Поэтому вам следует изменить 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()         
}

...