I am trying to develop my own weather app in Android Studios. So far my application successfully connects to an API and parses the json data received. It then displays a 7 day forecast using a ListView and the getView method by displaying each day and its forecast contents in a seperate row.
I am also attempting to display the Location of the forecast data in a TextView. So, at the top of my activity it will say "London" followed by a ListView of X amount of rows depending on how many days forecast it is showing.
My JSONParser class returns an ArrayList which contains the data for each day. I have used a forloop to loop through the JSON array to retrieve each day of the forecast.
One slight issue I am facing is that I currently am retrieving the Location String from the API (E.G "London") inside the forloop, which is not necessary as I only need to retrieve this value once, instead of X amount of times as per the array length.
JSONParser Class:
public class JSONParser {
public static List<ForecastModel> getForecast(String data) {
List<ForecastModel> forecastModelList = new ArrayList<>();
DateFormat dateFormat = DateFormat.getDateInstance();
try {
JSONObject mainObject = new JSONObject(data);
JSONArray jsonArray = mainObject.getJSONArray("data");
ForecastModel location = new ForecastModel();
//set city name
location.setCityName(mainObject.getString("city_name"));
forecastModelList.add(location);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject forecastObject = jsonArray.getJSONObject(i);
ForecastModel forecastModel = new ForecastModel();
forecastModel.setTimeStamp(forecastObject.getString("ts"));
//get city name
forecastModel.setCityName(mainObject.getString("city_name"));
//Format UNIX time stamp
Date forecastDate = new Date((forecastObject.getLong("ts") * 1000L));
String formattedDate = dateFormat.format(forecastDate);
forecastModel.setTimeStamp(formattedDate);
forecastModel.setTemp(forecastObject.getDouble("temp"));
forecastModel.setMaxTemp(forecastObject.getDouble("max_temp"));
forecastModel.setMinTemp(forecastObject.getDouble("min_temp"));
forecastModel.setWindSpeed(forecastObject.getDouble("wind_spd"));
JSONObject weatherObj = forecastObject.getJSONObject("weather");
forecastModel.setCondition(weatherObj.getString("description"));
forecastModelList.add(forecastModel);
}
} catch (JSONException e) {
e.printStackTrace();
}
return forecastModelList;
}
}
The app displays the expected results,but with the Location being added to every iteration of the forloop.
I have attempted to add the location object to the list outside the forloop, except this will put it at 0th position in the arrayList and the first row in my ListView returns null data.