简体   繁体   中英

Android Kotlin Recycle View reloadData

I have "problem" with this:

在此处输入图像描述 ,

where P button is Previous, and N as Next, both button call:

private fun fetchJson(date: String) {
        val url = "https://xxx/$date.json"
        println("URL: $url")
        val request = Request.Builder().url(url).build()
        val client = OkHttpClient()
        client.newCall(request).enqueue(object: Callback {

            override fun onResponse(call: Call, response: Response) {
                val responseData = response.body()?.string()

                runOnUiThread {
                    var rows: List<Product> = emptyList()

                    try {
                        if (response.code() in 200..399) {
                            val gson = GsonBuilder().create()
                            rows = gson.fromJson(responseData, Array<Product>::class.java).toList()

                            recycleView.adapter = ProductsAdapter(this@DetailsActivity, rows)
                            (recycleView.adapter as ProductsAdapter).notifyDataSetChanged()

                        }
                    } catch (e: JSONException) {
                        e.printStackTrace()
                    }
                }

            }

            override fun onFailure(call: Call, e: IOException) {
                println("Failed")
            }
        })
    }

and Products Adapter Class

class ProductsAdapter(private val context: Context, private val rows: List<Product>): RecyclerView.Adapter<ProductsAdapter.ProductViewHolder>() {

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ProductViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.product_item, parent, false)
        return ProductViewHolder(view)
    }

    override fun getItemCount(): Int {
        return rows.size
    }

    override fun onBindViewHolder(holder: ProductViewHolder, position: Int) {
        val row = rows[position]
        holder.setData(row, position)
    }

    inner class ProductViewHolder(itemView: View): RecyclerView.ViewHolder(itemView) {
        fun setData(row: Product, position: Int) {
            /// set data
        }
    }
}

also XML for recycle view is:

<androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycleView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:background="#E9DA1616"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/vipBtn" />

and the main problem is when tap on N or P button, data is there but recyclerView did not reload with new data. Only show product (populate recyclerview) first time.

Where I go wrong? I just start with Android and Kotlin, every tutorial says notifyDataSetChanged() this will do the job, but not...

Thanks

Maybe try recyclerView.invalidate() after pass new data

Wow! Just wow!

I have some experience in iOS and this is literally my 10th hour of Android development, but this is so strange.

My layout from question is constraint layout:

<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/colorPrimary"
    tools:context=".DetailsActivity">
[...]

I just change to relative layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#0A7463">
[...]

and now it's working. Amazing.

This is strange that layout define behavior of component.

To Reload the data in recyclerview you can use below things. First, add this method in your adapter class.

public fun setData(rowData:List<Product>){
   this.row = rowData
   notifyDataSetChanged()
}

After that below these lines in

private fun fetchJson(date: String) {
    val url = "https://xxx/$date.json"
    println("URL: $url")
    val request = Request.Builder().url(url).build()
    val client = OkHttpClient()
    client.newCall(request).enqueue(object: Callback {

        override fun onResponse(call: Call, response: Response) {
            val responseData = response.body()?.string()

            runOnUiThread {
                var rows: List<Product> = emptyList()

                try {
                    if (response.code() in 200..399) {
                        val gson = GsonBuilder().create()
                        rows = gson.fromJson(responseData,Array<Product>::class.java).toList()

                        recycleView.adapter.setData(rows)


                    }
                } catch (e: JSONException) {
                    e.printStackTrace()
                }
            }

        }

        override fun onFailure(call: Call, e: IOException) {
            println("Failed")
        }
    })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM