我的MainActivity
的onCreate()
包含这部分代码:
val weatherService = RetrofitFactory.retrofit(AppConstants.OWM_API_URL)
.create(OwmApi::class.java)
GlobalScope.launch(Dispatchers.Main) {
val request = weatherService.getCurrentWeatherDataByName("Bengaluru", "metric")
Log.i("Response 0", 0.toString())
try {
val response = request.await()
if(response.isSuccessful) {
Log.i("Response 2", 2.toString())
val weatherResponse = response.body()
Log.i("Response 3", 3.toString())
Log.i("Response", weatherResponse.toString())
println(weatherResponse)
}
else {
Log.i("Response 5", 5.toString())
Log.d(TAG, response.errorBody().toString())
}
}
catch (e: Exception) {
e.stackTrace
}
}
weatherService
的客户端包含一个拦截器,其定义如下:
private val loggingInterceptor = HttpLoggingInterceptor().apply {
level = HttpLoggingInterceptor.Level.BODY
}
现在,当我运行我的应用程序时,我只看到带有 Response 0 标记的日志,但看不到 Response,甚至在我更改时看不到代码的 else
部分查询参数为无效值。也许这与 loggingInterceptor
有关,但我仍然不确定为什么尽管 response.isSuccessful
部分为真,但某些日志消息没有出现。
最佳答案
你必须在后台线程中调用你的 api 调用,可能会出现异常。
所以像下面这样尝试
val weatherService = RetrofitFactory.retrofit(AppConstants.OWM_API_URL)
.create(OwmApi::class.java)
GlobalScope.launch(Dispatchers.IO) {
val request = weatherService.getCurrentWeatherDataByName("Bengaluru", "metric")
Log.i("Response 0", 0.toString())
try {
val response = request.await()
if(response.isSuccessful) {
Log.i("Response 2", 2.toString())
val weatherResponse = response.body()
Log.i("Response 3", 3.toString())
Log.i("Response", weatherResponse.toString())
println(weatherResponse)
}
else {
Log.i("Response 5", 5.toString())
Log.d(TAG, response.errorBody().toString())
}
}
catch (e: Exception) {
e.stackTrace
}
}
关于android - 无法记录某些行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58914950/