我正在使用Retrofit2和Kotlin Coroutines从api中获取数据以显示在RecycerView中。我刚刚开始学习Retrofit和Coroutines,目前数据还没有显示,我不确定如何解决!我认为问题可能出在协程代码上。请有人能帮我些忙吗?
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
var recyclerView: RecyclerView = findViewById(R.id.rockets_list)
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = RecyclerAdapter(List<RocketData>())
CoroutineScope(IO).launch {
val response = ApiInterface.getApi().getRockets()
Log.i("code",response.toString())
withContext(Dispatchers.Main) {
try {
if (response.isSuccessful) {
recyclerView.adapter
} else {
Toast.makeText(this@MainActivity, "Error ${response.code()}", Toast.LENGTH_SHORT).show()
}
} catch (e: HttpException) {
Toast.makeText(this@MainActivity, "Exception ${e.message}", Toast.LENGTH_SHORT).show()
}
}
}
}
}
interface ApiInterface {
@GET("rockets")
suspend fun getRockets(): Response<List<RocketData>>
companion object {
fun getApi(): ApiInterface = Retrofit.Builder()
.baseUrl("https://api.spacexdata.com/v3/")
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(ApiInterface::class.java)
}
}
最佳答案
response.isSuccessful
检查后您在做什么?
尝试在Adapter中设置响应,然后notifyDataSetChanged
recyclerView.adapter.items = response
recyclerView.adapter.notifyDataSetChanged()
关于api - 如何在Retrofit2中使用协程?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/59007591/