在 JSON 数据上使用 IF 语句出错(Android Kotlin)
using IF statement on JSON data goes wrong (Android Kotlin)
我正在尝试显示 5 天的天气预报,但 openweathermap 为我提供了 5 days/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"
}
所以有几件事你必须改变。
您添加的 IF 语句仅设置条件文本,其余部分保留默认字符串。为此,一种更改代码的方法如下所示。这将删除您额外的 TextView。
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 天气数据。您可以 google 如何使用 list.filter{predicate} 方法过滤列表。
必须以某种方式完成解析日期以获得 15:00:00 时间并添加 if 条件仅用于 15:00:00
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
}
已编辑:
向您的适配器添加一个变量 class
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()
我正在尝试显示 5 天的天气预报,但 openweathermap 为我提供了 5 days/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"
}
所以有几件事你必须改变。
您添加的 IF 语句仅设置条件文本,其余部分保留默认字符串。为此,一种更改代码的方法如下所示。这将删除您额外的 TextView。
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 天气数据。您可以 google 如何使用 list.filter{predicate} 方法过滤列表。
必须以某种方式完成解析日期以获得 15:00:00 时间并添加 if 条件仅用于 15:00:00
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 }
已编辑:
向您的适配器添加一个变量 class
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()