我想做一个应用程序,显示最近15场比赛和下15场比赛使用API。我创建了一个有2个不同列表视图的RecyclerView。一个用于上一场比赛,另一个用于下一场比赛。我还创建了两个不同的适配器,所以当我单击不同的导航栏时,它会将视图(例如last match)更改为另一个视图(Next match)。然而,当我点击第二个按钮(Next match)时,它会强制停止。
我认为问题出在适配器组中,但我不知道在哪里
以下是我的代码:
MainActivity.kt
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
//Prev Match
recyclerView_main.layoutManager = LinearLayoutManager(this)
fetchJsons()
return@OnNavigationItemSelectedListener true
}
R.id.navigation_dashboard -> {
//Next Match
recyclerView_main.layoutManager = LinearLayoutManager(this)
fetchJson()
return@OnNavigationItemSelectedListener true
}
}
false
}
fun fetchJsons(){
//Json for prev match
val url = "https://www.thesportsdb.com/api/v1/json/1/eventspastleague.php?id=4328"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback{
override fun onResponse(call: Call?, response: Response?){
println("sukses")
val body = response?.body()?.string()
println(body)
val gson = GsonBuilder().create()
val prevMatch = gson.fromJson(body, PrevMatch::class.java)
runOnUiThread { recyclerView_main.adapter = MainAdapters(prevMatch) }
}
override fun onFailure(call: Call?, e: IOException?){
println("failed request")
}
})
}
// Next Match JSON
fun fetchJson(){
val url = "https://www.thesportsdb.com/api/v1/json/1/eventsnextleague.php?id=4328"
val request = Request.Builder().url(url).build()
val client = OkHttpClient()
client.newCall(request).enqueue(object: Callback{
override fun onResponse(call: Call?, response: Response?){
println("sukses")
val body = response?.body()?.string()
println(body)
val gson = GsonBuilder().create()
val nextMatch = gson.fromJson(body, NextMatch::class.java)
runOnUiThread { recyclerView_main.adapter = MainAdapter(nextMatch) }
}
override fun onFailure(call: Call?, e: IOException?){
println("failed request")
}
})
}
发布于 2018-09-04 06:58:59
下面是我要做的,我将创建两个recyclerView并在它们之间切换。并在它们之间划分来自API的数据。
private val mOnNavigationItemSelectedListener = BottomNavigationView.OnNavigationItemSelectedListener { item ->
when (item.itemId) {
R.id.navigation_home -> {
//Prev Match
recyclerView_Next_Match.visibility = View.GONE
recyclerView_Prev_Match.visibility = View.VISIBLE
fetchJsons()
return@OnNavigationItemSelectedListener true
}
R.id.navigation_dashboard -> {
//Next Match
recyclerView_Prev_Match.visibility = View.GONE
recyclerView_Next_Match.visibility = View.VISIBLE
fetchJson()
return@OnNavigationItemSelectedListener true
}
}
false
}
https://stackoverflow.com/questions/52152682
复制相似问题