首页 > 解决方案 > 使用 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()
            }
    }

}

标签: androidkotlinretrofit

解决方案


请尝试实现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>
}

推荐阅读