【发布时间】:2020-03-19 07:32:02
【问题描述】:
我正在使用 Retrofit2 和 Kotlin 协程从 api 获取数据以显示在 RecycerView 中。我刚刚开始学习改造和协程,目前数据没有显示,我不知道如何解决它!我认为问题可能出在协程代码上。请问有人可以帮我吗?
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)
}
}
【问题讨论】:
-
如我所见,您在检查
if (response.isSuccessful)后没有更新适配器项目@
标签: api kotlin android-recyclerview retrofit kotlin-coroutines