【发布时间】:2021-06-06 20:23:28
【问题描述】:
我有一个问题:我正在使用 Retrofit 2.0 编写一个天气应用程序。当我在模拟器上运行应用程序时,一切正常(API 24、28、29)。但是今天我在物理设备(Galaxy A21s,版本 android 10)上启动了我的应用程序,并且对服务器的请求不起作用。该请求适用于Response(),但它带有 response.body () = = null 和 response.is Success == null。但一切都在模拟器中工作! 您能告诉我们问题是什么以及如何解决吗?
class DataProcessing {
private val retrofitImpl: RetrofitImpl = RetrofitImpl()
private val mainActivity = MainActivity()
internal fun sendRequest(townName:String, instance : DataProcessingCallback){
retrofitImpl.getRequest().showWeather(townName).enqueue(object : Callback<DateWeather> {
override fun onResponse(call: retrofit2.Call<DateWeather>, response: Response<DateWeather>) {
if (response.isSuccessful && response.body() != null) {
processingData(response.body(), null, instance)
} else
processingData(null, Throwable("ответ не получен"), instance)
}
override fun onFailure(call: Call<DateWeather>, t: Throwable) {
Log.d("Main", "onFailure")
processingData(null, t, instance)
}
})
}
private fun processingData(dateWeather:DateWeather?, error: Throwable?, instance : DataProcessingCallback){
if (dateWeather == null || error != null) {
Log.d("Egor", "error: ${error!!.message.toString()}")
instance.showToastText("Произошла ошибка \n Возможно вы неправильно ввели название населенного пункта")
} else {
if (dateWeather == null) Log.d("Main", "Loose")
else {
val string = dateWeather.weather.get(0).toString()
val size = string.length - 1
instance.onSuccessfulDataProcessed(string.subSequence(13, size).toString(), dateWeather.main.temp!!.toInt())
}
}
}
}
interface ShowWeather{
@GET("weather?&appid=(TOKEN)&units=metric")// there is a token here, I just deleted it when publishing, everything is fine with it
fun showWeather(@Query("q") town: String): Call<DateWeather>
}
class RetrofitImpl{
fun getRequest() : ShowWeather{
val retrofitBuilder = Retrofit.Builder()
.baseUrl("http://api.openweathermap.org/data/2.5/")
.addConverterFactory(GsonConverterFactory.create())
.build()
return retrofitBuilder.create(ShowWeather::class.java)
}
}
data class DateWeather(
val main: Main,
val weather : List<Weather>
)
data class Main(
val temp : Double?
)
data class Weather(
val main: String
)
【问题讨论】:
标签: android kotlin retrofit samsung-galaxy