[英]How to reset the content of recycler view in calling activity using Kotlin
What I want to do: As user type something in edittext, a API call and show the response in recyclerview. 我想做什么:当用户在edittext中键入一些内容时,将调用一个API并在recyclerview中显示响应。
in OnCreate() 在OnCreate()中
usersData= ArrayList()
resultRecyclerView.setHasFixedSize(true)
resultRecyclerView.layoutManager=LinearLayoutManager(
this@MainActivity,LinearLayoutManager.VERTICAL,false)
itemsAdapter=adapter(this@MainActivity,usersData)
resultRecyclerView.adapter=itemsAdapter
in OnResume() 在OnResume()中
searchText.addTextChangedListener(object : TextWatcher {
override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
//....
}
override fun beforeTextChanged(s: CharSequence, start: Int, count: Int, after: Int) {
//.......
}
override fun afterTextChanged(s: Editable) {
Log.v("Text is ",s.toString())
val url="https://api.github.com/search/users?q="+s.toString().trim()+"+sort:followers"
fetchData(url)
}
})
Method for fetching data 数据获取方法
private fun fetchData(url: String) {
val tag_string_req = "string_req"
val strReq = StringRequest(Request.Method.GET,
url, Response.Listener<String> {
response ->
Log.d(TAG, response.toString())
val builder = GsonBuilder()
val gson = builder.create()
//val allItems=gson.fromJson(response,AllUsers::class.java)
val data=gson.fromJson(response,AllUsers::class.java)
usersData=data.items
Log.v("No of users",usersData?.size.toString())
resultRecyclerView.removeAllViews()
itemsAdapter?.notifyDataSetChanged()
}, Response.ErrorListener { error ->
VolleyLog.d(TAG, "Error: " + error.message)
})
// Adding request to request queue
AppController.getInstance().addToRequestQueue(strReq, tag_string_req)
}
But updated data is not passing in the adapter (it still have zero data). 但是更新的数据没有传递到适配器中(它仍然有零个数据)。 I getting the expected response from the
API
. 我从
API
获得预期的响应。 notifyDataSetChanged()
is not updating the list. notifyDataSetChanged()
不更新列表。
I thought notifyDataSetChanged also update the data automatically but no. 我以为notifyDataSetChanged也会自动更新数据,但是没有。
I need to call 我需要打电话
itemsAdapter?.updateData(usersData)
and in adapter: 并在适配器中:
fun updateData(users: ArrayList<Items>?){
this.users=users
}
Add this method in adapter 在适配器中添加此方法
fun addData(exList: MutableList<Object>) {
items.clear()
items.addAll(exList)
notifyDataSetChanged()
}
and add data from your activity/fragment like this 并像这样从您的活动/片段中添加数据
projectsAdapter.addData(list as MutableList<Object>)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.