android - 使用 Kotlin 和 Retrofit 的 Android 项目中未解决的参考 call.enqueue 错误
问题描述
我是 android 新手,我在 mainactivity.kt 文件中有一个未解决的入队错误。我正在使用改造从 https://jsonplaceholder.typicode.com/posts检索数据
Posts
数据类
class Posts : ArrayList<PostsItem>()
PostsItem
数据类
data class PostsItem(
val userId: Int,
val id: Int,
val title: String,
val body: String
)
PostsService
界面
import retrofit2.Response
import retrofit2.http.GET
interface PostsService {
@GET("posts")
fun getPosts() : Response<Posts>
}
MainActivity.kt
我面临未解决的入队错误的文件
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val retrofit = Retrofit.Builder()
.baseUrl("https://jsonplaceholder.typicode.com/")
.addConverterFactory(GsonConverterFactory.create())
.build()
val postsService = retrofit.create(PostsService::class.java)
val call = postsService.getPosts()
//IT SAYS UNRESOLVED REFERENCE enqueue
call.enqueue(object : Callback<Posts>){
override fun onResponse(call: Call<Posts>, response: Response<Posts>){
if (response.isSuccessful){
Toast.makeText(this@MainActivity, "success", Toast.LENGTH_SHORT).show()
}
}
override fun onFailure(call: Call<Posts>, t: Throwable) {
Toast.makeText(this@MainActivity, "${t.message}", Toast.LENGTH_SHORT).show()
}
}
}
解决方案
请尝试实现onFailure()
方法:
call.enqueue(object : Callback<Posts> {
override fun onFailure(call: Call<Posts>, t: Throwable?) {
// TODO implement me
}
override fun onResponse(call: Call<Posts>, response: Response<Posts>) {
// TODO implement me
}
})
请查看改造文档
另外,将界面更改如下:-
interface PostsService {
@GET("posts")
fun getPosts() : Call<Posts>
}
推荐阅读
- java - 测试 dockerfile 中忽略的 xml
- sql - SQL 查询以引用其中 xxcolumnxxx 中(数千个列表)中的大型值列表(即创建可以在查询之间持续存在的子集?)
- r - R / Bookdown:在 render_book() 函数中指定 rmd_files
- javascript - webpack 是捆绑 Node.js 后端代码的合适工具吗?
- sql - 如何在 SQL 中仅选择当前月份数据?
- javascript - 为什么我的 JavaScript 函数在我告诉它在另一个函数运行时停止时继续运行?
- c++ - 巨大的数字而不是 0 和浮点数
- java - 当我尝试运行 appium 自动化项目时,方法 getBinaryPath() 未定义为 Eclipse 中显示的类型 WebDriverManager 错误
- laravel - 原始选择 Laravel - 'ST_Transform' 不是公认的内置函数名称
- java - 在 JDK11 中使用 ToStringBuilder.reflectionToString() 对象到字符串