我正在尝试本地访问api,但是onResponse方法不起作用onFailure方法始终运行
class Categories : Fragment() {
lateinit var categories_recycler: RecyclerView
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val v = inflater!!.inflate(R.layout.fragment_categories, container, false)
categories_recycler = v.findViewById(R.id.categories_recycler)
categories_recycler.setHasFixedSize(true)
categories_recycler.layoutManager = LinearLayoutManager(activity)
retrofit()
return v
}
fun retrofit(){
val retrofit = RetrofitBuilder.instance
val client = retrofit.create(SkillClientRetrofit::class.java)
val call = client.CategoryNames()
call.enqueue(object : Callback< List< GetCatName>> {
override fun onResponse(call: Call< List< GetCatName>>, response: Response< List< GetCatName>>) {
if(response.isSuccessful) {
activity.toast("this is success")
val data = response.body()
categories_recycler.adapter = CategoriesSkillAdapter(data!!)
}
}
override fun onFailure(call: Call< List< GetCatName>>, t: Throwable) {
activity.toast("this is error")
}
})
}
}
以下是RetrofitBuilder:
object RetrofitBuilder {
private var r: Retrofit? = null
val instance:Retrofit
get(){
if(r == null){
r = Retrofit.Builder().baseUrl("<http://192.168.56.1:3000/>")
.addConverterFactory(GsonConverterFactory.create())
.build()
}
return r!!
}
}
下面是界面:
public interface SkillClientRetrofit
{ @GET(" category/names") fun CategoryNames(): Call< List< GetCatName>> }
这是数据类:
data class GetCatName(
@SerializedName("_id") val id: String,
@SerializedName("category_name") val categoryName: String )