【发布时间】:2021-09-29 03:59:39
【问题描述】:
您好,我正在尝试使用改造进行基本的 api 调用,并将对象放在 recyclerview 上。下面是Retrofit Instance、service、viewmodel的代码。
SearchFragmentViewModel.kt
class SearchFragmentViewModel(application: Application): AndroidViewModel(application){
var eventSearchList: MutableLiveData<ArrayList<EventSearchData>>
// var eventSearchList: MutableLiveData<EventSearchList>
val TAG:String = "demo"``
init {
eventSearchList = MutableLiveData()
//getDataFromApi("")
}
fun getRecyclerListDataObserver(): MutableLiveData<ArrayList<EventSearchData>> {
return eventSearchList
}
fun getDataFromApi(tempString: String) {
val TAG: String = "demo"
viewModelScope.launch(Dispatchers.IO) {
val retroInstance = RetrofitInstance.getRetrofitInstance()
.create(RetrofitService::class.java)
val call = retroInstance.getEventDataFromApi(tempString) //from this point not working
if (call.isExecuted){
Log.d(TAG, "if call is excecuted")
}
call.enqueue(object :retrofit2.Callback<EventSearchList>{
override fun onResponse(call: Call<EventSearchList>, response: Response<EventSearchList>) {
Log.d(TAG, "onResponse: on success")
if (response.isSuccessful){
eventSearchList.postValue(response.body()?.event)
Log.d(TAG, "onResponse: ${response.body()}")
}else{
eventSearchList.postValue(null)
}
}
override fun onFailure(call: Call<EventSearchList>, t: Throwable) {
eventSearchList.postValue(null)
Log.d(TAG, "onFailure: call retrofit") }
})
Log.d(TAG, "onFailure: dfdag refdhdfhtrofit")
}
}
}
RetroInstance.kt
class RetrofitInstance {
companion object{
val BASE_URL ="https://www.thesportsdb.com/api/v1/json/1/"
fun getRetrofitInstance(): Retrofit {
return Retrofit.Builder()
.baseUrl(BASE_URL)
.addConverterFactory(GsonConverterFactory.create())
.build()
}
}
}
RetrofitService.kt
interface RetrofitService {
@GET("searchevents.php")
suspend fun getEventDataFromApi(@Query("e") query: String): Call<EventSearchList>
}
从视图模型中的调用方法,没有得到任何东西,(起初我试图显示response.body,但没有成功)最终在调试了我资助的代码之后,没有LogCat被打印出来。请让我知道我做错了什么。
P.S - 尝试检查 android:textTraffic="true, 用于改造 2 库实现的 gradle 文件, 使用回调和不使用回调,但没有任何东西通过逆向服务调用
【问题讨论】:
标签: android api kotlin mvvm retrofit