【问题标题】:RetrofitService not getting called/working and has no error either Android Retrofit, Kotlin, ViewmodelRetrofitService 没有被调用/工作,并且 Android Retrofit、Kotlin、Viewmodel 也没有错误
【发布时间】: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


    【解决方案1】:

    查看您的代码,您正在尝试同时使用两种不同的线程工具,但这是行不通的。一个是coroutines,第二个是enqueue。如果你想使用 enqueue,你不必在你的界面中暂停你的 GET 乐趣,即它看起来像这样

    interface RetrofitService {
    
    @GET("searchevents.php") fun getEventDataFromApi(@Query("e") query: String): Call 
    }
    

    您还必须像这样使用 Call 将响应类包装在接口中

    interface RetrofitService {
    
    @GET("searchevents.php") suspend fun getEventDataFromApi(@Query("e") query: String): Call<EventSearchList> 
    }
    

    如果 EventSearchList 是您预期的 API 响应。

    因此,不需要 ViewModel 中的协程范围。你的电话看起来像

     fun getDataFromApi(tempString: String) {
    val call = retroInstance.getEventDataFromApi(tempString)
     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")                 }
    
             })
    
     }
    
    

    另外,我不知道你的retrofit2是什么意思。我想你会明白的。

    我还会建议您将 OKHTTP Interceptor https://blog.mindorks.com/okhttp-interceptor-making-the-most-of-it 添加到您的改造中,以了解您的网络调用出了什么问题

    class RetrofitInstance {
    
    companion object{
        val BASE_URL ="https://www.thesportsdb.com/api/v1/json/1/"
    
        fun getRetrofitInstance(): Retrofit {
    
            return Retrofit.Builder()
                 .client(OkHttpClient.Builder().addInterceptor(HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY)).build())
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .build()
        }
    }
    
    

    对于协程,您可以查看https://blog.mindorks.com/using-retrofit-with-kotlin-coroutines-in-android 并将其与您的工作联系起来

    【讨论】:

    • 谢谢@user11874398,你拯救了我的一天!!,它成功了。我在想 APImethod 调用应该写成“暂停乐趣”
    • 我很高兴它有帮助。您能否将答案标记为已接受? @nikhilsurya
    • 我做了@user11874398
    猜你喜欢
    • 1970-01-01
    • 2012-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-17
    • 1970-01-01
    • 1970-01-01
    • 2013-05-20
    相关资源
    最近更新 更多