我尝试使用 Retrofit 和 Android 架构组件调用 API,但收到此错误
java.lang.RuntimeException: Failed to invoke public android.arch.lifecycle.LiveData() with no args
这是响应的数据类
data class ForecastResult(val city: City, val list: List<Forecast>)
服务接口(interface)
interface ServicesApis { // using dummy data
@GET("data/2.5/forecast/")
fun getForecast(@Query("APPID") APPID: String = "xxxxxxxx"
, @Query("q") q: String = "94043", @Query("mode") mode: String = "json", @Query("units") units: String = "metric"
, @Query("cnt") cnt: String = "7"): Call<LiveData<ForecastResult>>
}
和API实现
class WeatherRepoImpl : WeatherRepo {
override fun getDailyForecast(): LiveData<Resource<ForecastResult>> {
val forecast: MutableLiveData<Resource<ForecastResult>> = MutableLiveData()
RestAPI.getAPIsrevice().getForecast().enqueue(object : Callback<LiveData<ForecastResult>> {
override fun onResponse(call: Call<LiveData<ForecastResult>>?, response: Response<LiveData<ForecastResult>>?) {
when {
response!!.isSuccessful -> {
forecast.postValue(Resource.success(response.body()?.value))
}
else -> {
val exception = AppException(responseBody = response.errorBody())
forecast.postValue(Resource.error(exception))
}
}
}
override fun onFailure(call: Call<LiveData<ForecastResult>>?, t: Throwable?) {
val exception = AppException(t)
forecast.postValue(Resource.error(exception))
}
})
return forecast
}
}
感谢您的帮助!
最佳答案
从 API 调用中删除 LiveData,并创建 MutableLiveData
对象中包含的 ViewModel
类。
例如:
API 调用定义如下:(删除 LiveData)
@GET("data/2.5/forecast/")
fun getForecast(@Query("APPID") APPID: String = "xxxxxxxx"
, @Query("q") q: String = "94043", @Query("mode") mode: String = "json", @Query("units") units: String = "metric"
, @Query("cnt") cnt: String = "7"): Call<ForecastResult>
创建一个 ViewModel 类:
class YourViewModel: ViewModel() {
var allObjLiveData = MutableLiveData<YOUROBJECT>()
fun methodForAPICall(){
mApiService?.getForecast(.....)?.enqueue(object : Callback<YOUROBJECT>
{
override fun onFailure(call: Call<YOUROBJECT>, t: Throwable) {
allObjLiveData.value = null
}
override fun onResponse(call: Call<YOUROBJECT>, response: Response<YOUROBJECT>) {
allObjLiveData.value=response.body() //Set your Object to live Data
}
})
}
}
现在在您的 Activity 或 fragment 中初始化 ViewModel 类。 并观察实时数据。
yourViewModelClassObj?.allObjLiveData?.observe(this, Observer {
//whenever object change this method call every time.
}
})
因此您可以在 ViewModel 类中使用 livedata。
关于android - java.lang.RuntimeException : Failed to invoke public android. arch.lifecycle.LiveData() 没有参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49280365/