【问题标题】:using IF statement on JSON data goes wrong (Android Kotlin)对 JSON 数据使用 IF 语句出错(Android Kotlin)
【发布时间】:2018-08-20 18:25:40
【问题描述】:

我正在尝试显示 5 天的天气预报,但 openweathermap 为我提供了 5 天/3 小时的天气。我想做的是只显示 15:00 的天气。

我正在使用带有日期和时间之一的 if 语句,如果您看到我的模拟器,它会多次显示相同的日期和时间,并将整个 JSON 文件显示为空文本。请问对此有什么想法吗?

这是我的 if 语句

if(weatherFor.dt_txt=="2018-08-21 00:00:00") {
            holder?.view?.textWeatherDataForecast?.text = "${weatherFor.weather.map { it.description }.joinToString(",")} on ${date}"
            holder?.view?.tempTextForecast?.text = weatherFor.main.temp.toString() + "°C"

        }

【问题讨论】:

  • 您能粘贴一个示例响应吗?
  • @karthikprasad 你是什么意思?(对不起,我是新手)
  • 你能分享你的 ForecastWeatherList 对象吗?

标签: android json if-statement kotlin openweathermap


【解决方案1】:

所以有几件事你必须改变。

  1. 您添加的 IF 语句只是为条件设置文本,其余的保留默认字符串。为此,一个 hack 可以更改如下代码。这将删除您额外的 TextViews。

    if(weatherFor.dt_txt=="2018-08-21 00:00:00") 
    {
           holder?.view?.textWeatherDataForecast?.text = "${weatherFor.weather.map { it.description }.joinToString(",")} on ${date}"
        holder?.view?.tempTextForecast?.text = weatherFor.main.temp.toString() + "°C"
    
    }
    else
    { 
         holder?.view?.visibility = View.GONE
    }
    

但理想情况下,您必须过滤您的响应以在列表中仅包含 15:00 的天气数据。你可以谷歌如何使用 list.filter{predicate} 方法过滤列表。

  1. 解析日期必须以获取 15:00:00 时间的方式完成,并添加仅针对 15:00:00 的 if 条件

     val localDateFormat = SimpleDateFormat("HH:mm:ss")
    val dt_time: String = localDateFormat.format(date)
    
     if(dt_time == "15:00:00"){
            // your set holder text goes here
     }
    

已编辑:

为你的适配器类添加一个变量

    lateinit var weatherList: List<ForecastWeatherList>

添加一个初始化块

    init{
        weatherList = forecastfeed.list.filter{ //add your condition here this should plain condition which gives true or false like it.dt_txt =="15:00:00" }
    }

在你的 getItemCount() 替换

    weatherList.count()

【讨论】:

  • 哦,非常感谢!!!现在的问题是它显示了我想要的,但它有一个很大的白色间隙。如果时间不是 3 点,我们怎么能不添加所有元素?
  • 您必须根据时间过滤列表内容。编辑了答案。如果有帮助,请接受并支持答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-26
  • 1970-01-01
  • 2021-04-02
  • 1970-01-01
相关资源
最近更新 更多