【问题标题】:How do i check if a Api response exists如何检查 Api 响应是否存在
【发布时间】:2022-01-18 01:25:55
【问题描述】:
我不断收到一个空指针异常,我想查看响应是否存在,如果存在则将其打印出来。
if (responsePlace.result.opening_hours.weekday_text.isNotEmpty() ){
println("The response for place time " + responsePlace.result.opening_hours.weekday_text[0].toString())}
【问题讨论】:
标签:
android
kotlin
retrofit
【解决方案1】:
你可以试试这个:
responsePlace.let
{
when(it.isSuccessful) {
true -> println(""The response for place time " + it.result.opening_hours.weekday_text[0].toString()")
false -> println("something went wrong!")
}
【解决方案2】:
在 kotlin 中使用方便的 isNullOrEmpty() 方法。
所以你的方法看起来像
if (!responsePlace.result.opening_hours.weekday_text.isNullOrEmpty()){
println("The response for place time " + responsePlace.result.opening_hours.weekday_text[0].toString())}
注意“!”条件开头的否定
【解决方案3】:
您必须检查哪个对象为空或更好地发布日志跟踪。
您可以使用 Kotlin 安全调用来防止 NPE。
if(responsePlace?.result?.opening_hours.weekday_text.isNullOrEmpty())
println("The response for place time " + responsePlace.result.opening_hours.weekday_text[0].toString())