Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Data in my ArrayList is always overwritten but I need it to remember the previous values

I get JSON from weather API, it contains Array of date and time, temperatures, wind speed, etc.

I tried to create a new conditionArray in which correspondence between the weather condition and date (time) is set and each of its elements will represent the dependence of weather conditions on time. But in my case only the last element of conditionArray is shown.

public class WeatherActivity extends AppCompatActivity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather);
        int District = getIntent().getIntExtra("District", -1);
        String latitude="";
        String longitude="";
        switch (District) {
            case 0:
                latitude = "55.753600";
                longitude = "37.621184";
                break;
            case 1:
                latitude = "55.838390";
                longitude = "37.525774";
                break;
            case 2:
                latitude = "55.854875";
                longitude = "37.632565";
                break;
            case 3:
                latitude = "55.787715";
                longitude = "37.775631";
                break;
            case 4:
                latitude = "55.692019";
                longitude = "37.754592";
                break;
            case 5:
                latitude = "55.622014";
                longitude = "37.678065";
                break;
            case 6:
                latitude = "55.662735";
                longitude = "37.576187";
            case 7:
                latitude = "55.778003";
                longitude = "37.443533";
                break;
            case 8:
                latitude = "55.829370";
                longitude = "37.451555";
                break;
            case 9:
                latitude = "55.987583";
                longitude = "37.194250";
                break;
            case 10:
                latitude = "55.355802";
                longitude = "37.146999";
                break;
            case 11:
                latitude = "55.594351";
                longitude = "37.371452";
                break;
            default:
                break;
        }
        String address = "https://api.open-meteo.com/v1/forecast?latitude=" + latitude + "&longitude=" + longitude + "&hourly=temperature_2m,relative_humidity_2m,apparent_temperature,precipitation_probability,snowfall,cloud_cover,wind_speed_10m&wind_speed_unit=ms&timezone=Europe%2FMoscow&forecast_days=1";

        new Thread(() -> {
            try {
                URL url = new URL(address);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");

                InputStream stream = connection.getInputStream();
                BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
                StringBuilder buffer = new StringBuilder();
                String line;
                while ((line = reader.readLine()) != null) {
                    buffer.append(line).append("\n");
                }
                String result = buffer.toString();
                if(reader!=null) {
                    try {

                        JSONObject object = new JSONObject(result);
                        JSONArray timeArray = object.getJSONObject("hourly").getJSONArray("time");
                        JSONArray temperatureArray = object.getJSONObject("hourly").getJSONArray("temperature_2m");
                        JSONArray humidityArray = object.getJSONObject("hourly").getJSONArray("relative_humidity_2m");
                        JSONArray precipitationArray = object.getJSONObject("hourly").getJSONArray("precipitation_probability");
                        JSONArray cloudArray = object.getJSONObject("hourly").getJSONArray("cloud_cover");
                        JSONArray windSpeedArray = object.getJSONObject("hourly").getJSONArray("wind_speed_10m");
                        JSONArray snowArray = object.getJSONObject("hourly").getJSONArray("snowfall");
                        for (int i = 0; i < timeArray.length(); i++) {
                            String time = timeArray.getString(i);
                            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
                            SimpleDateFormat outputFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
                            Date date = null;
                            try {
                                date = inputFormat.parse(time);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            String outputString = outputFormat.format(date);
                            String temperature = temperatureArray.getString(i);
                            String humidity = humidityArray.getString(i);
                            double precipitation = precipitationArray.getDouble(i);
                            double cloud = cloudArray.getDouble(i);
                            String windSpeed = windSpeedArray.getString(i);
                            String snowfall = snowArray.getString(i);
                            ArrayList<Condition> conditions = new ArrayList<>();
                            conditions.add(new Condition(outputString, temperature, humidity, precipitation, cloud, windSpeed, snowfall));
                            runOnUiThread(() -> {
                                RecyclerView rcView = findViewById(R.id.recyclerView2);
                                WeatherAdapter adapter = new WeatherAdapter(conditions);
                                rcView.setLayoutManager(new LinearLayoutManager(WeatherActivity.this, LinearLayoutManager.VERTICAL, false));
                                rcView.setAdapter(adapter);
                            });
                        }
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                connection.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }).start();
    }

}
public class Condition {
    private String time;
    private String temperature;
    private String humidity;
    private  double precipitation;
    private double cloud;
    private String windSpeed;
    private String snowfall;

    public Condition(String time, String temperature, String humidity, double precipitation, double cloud, String windSpeed, String snowfall) {
        this.time = time;
        this.temperature = temperature;
        this.humidity = humidity;
        this.precipitation = precipitation;
        this.cloud = cloud;
        this.windSpeed = windSpeed;
        this.snowfall = snowfall;
    }

    public String getTime() {
        return time;
    }

    public void setTime(String time) {
        this.time = time;
    }

    public String getTemperature() {
        return temperature;
    }

    public void setTemperature(String temperature) {
        this.temperature = temperature;
    }

    public String getHumidity() {
        return humidity;
    }

    public void setHumidity(String humidity) {
        this.humidity = humidity;
    }

    public double getPrecipitation() {
        return precipitation;
    }

    public void setPrecipitation(double precipitation) {
        this.precipitation = precipitation;
    }

    public double getCloud() {
        return cloud;
    }

    public void setCloud(double cloud) {
        this.cloud = cloud;
    }

    public String getWindSpeed() {
        return windSpeed;
    }

    public void setWindSpeed(String windSpeed) {
        this.windSpeed = windSpeed;
    }

    public String getSnowfall() {
        return snowfall;
    }

    public void setSnowfall(String snowfall) {
        this.snowfall = snowfall;
    }
}
public class WeatherAdapter extends RecyclerView.Adapter<WeatherAdapter.ViewHolder>{


    private ArrayList<Condition> conditions;

    public WeatherAdapter(ArrayList<Condition> conditions) {
        this.conditions = conditions;
    }

    public static class ViewHolder extends RecyclerView.ViewHolder{
        private final TextView dateView;
        private final TextView tempView;
        private final TextView humidView;
        private final TextView precView;
        private final ImageView imaView;
        private final TextView cloudView;
        private final TextView windView;
        ViewHolder(View view){
            super(view);
            dateView = view.findViewById(R.id.Date);
            tempView = view.findViewById(R.id.Temperature);
            humidView = view.findViewById(R.id.Humidity);
            precView = view.findViewById(R.id.Precipitation);
            imaView = view.findViewById(R.id.WeatherImage);
            cloudView= view.findViewById(R.id.Cloud);
            windView = view.findViewById(R.id.WindSpeed);
        }
    }

    @NonNull
    @Override
    public WeatherAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.weather_cardview,parent,false);
        return new WeatherAdapter.ViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull WeatherAdapter.ViewHolder holder, int position) {
        Condition condition = conditions.get(position);
        holder.dateView.setText(String.format("%s",condition.getTime()));
        holder.tempView.setText(String.format("Температура воздуха: %s ℃",condition.getTemperature()));
        holder.humidView.setText(String.format("Относительная влажность: %s ",condition.getHumidity()));
        holder.precView.setText(String.format("Вероятность осадков: %s",condition.getPrecipitation()));
        holder.cloudView.setText(String.format("Облачность: %s",condition.getCloud()));
        holder.windView.setText(String.format("Скорость ветра: %s м/с",condition.getWindSpeed()));
        if (condition.getPrecipitation()>=50 && condition.getSnowfall().equals("0,00") && condition.getCloud()>=50){
            holder.imaView.setImageResource(R.drawable.rainy);
        }
        else if (condition.getPrecipitation()>=50 && condition.getSnowfall().equals("0,00") && condition.getCloud()<50){
            holder.imaView.setImageResource(R.drawable.rain);
        }
        else if (condition.getPrecipitation()<50 && condition.getSnowfall().equals("0,00") && condition.getCloud()>=50){
            holder.imaView.setImageResource(R.drawable.cloudy);
        }
        else if (condition.getPrecipitation()<50 && condition.getSnowfall().equals("0,00") && condition.getCloud()<50 && condition.getCloud()>10){
            holder.imaView.setImageResource(R.drawable.cloudy_sunny);
        }
        else if (condition.getPrecipitation()<50 && condition.getSnowfall().equals("0,00") && condition.getCloud()<=10){
            holder.imaView.setImageResource(R.drawable.sunny);
        }
        else if (condition.getPrecipitation()>=50 && !condition.getSnowfall().equals("0,00") && condition.getCloud()>=50){
            holder.imaView.setImageResource(R.drawable.snowy);
        }
        else{
            holder.imaView.setImageResource(R.drawable.cloudy_sunny);
        }
    }

    @Override
    public int getItemCount() {
        return conditions.size();
    }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It’s because the you are creating an ArrayList each time you want to add to it, by mistake

if(reader!=null) {
                    try {

                        JSONObject object = new JSONObject(result);
                        JSONArray timeArray = object.getJSONObject("hourly").getJSONArray("time");
                        JSONArray temperatureArray = object.getJSONObject("hourly").getJSONArray("temperature_2m");
                        JSONArray humidityArray = object.getJSONObject("hourly").getJSONArray("relative_humidity_2m");
                        JSONArray precipitationArray = object.getJSONObject("hourly").getJSONArray("precipitation_probability");
                        JSONArray cloudArray = object.getJSONObject("hourly").getJSONArray("cloud_cover");
                        JSONArray windSpeedArray = object.getJSONObject("hourly").getJSONArray("wind_speed_10m");
                        JSONArray snowArray = object.getJSONObject("hourly").getJSONArray("snowfall");
                        for (int i = 0; i < timeArray.length(); i++) {
                            String time = timeArray.getString(i);
                            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
                            SimpleDateFormat outputFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
                            Date date = null;
                            try {
                                date = inputFormat.parse(time);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            String outputString = outputFormat.format(date);
                            String temperature = temperatureArray.getString(i);
                            String humidity = humidityArray.getString(i);
                            double precipitation = precipitationArray.getDouble(i);
                            double cloud = cloudArray.getDouble(i);
                            String windSpeed = windSpeedArray.getString(i);
                            String snowfall = snowArray.getString(i);
                            
                            conditions.add(new Condition(outputString, temperature, humidity, precipitation, cloud, windSpeed, snowfall));
                            runOnUiThread(() -> {
                                RecyclerView rcView = findViewById(R.id.recyclerView2);
                                WeatherAdapter adapter = new WeatherAdapter(conditions);
                                rcView.setLayoutManager(new LinearLayoutManager(WeatherActivity.this, LinearLayoutManager.VERTICAL, false));
                                rcView.setAdapter(adapter);
                            });
                        }
                    }
                    catch (JSONException e) {
                        e.printStackTrace();
                    }

Should be corrected to

// Moved this outside the loop
ArrayList<Condition> conditions = new ArrayList<>();

if(reader!=null) {
                    try {

                        JSONObject object = new JSONObject(result);
                        JSONArray timeArray = object.getJSONObject("hourly").getJSONArray("time");
                        JSONArray temperatureArray = object.getJSONObject("hourly").getJSONArray("temperature_2m");
                        JSONArray humidityArray = object.getJSONObject("hourly").getJSONArray("relative_humidity_2m");
                        JSONArray precipitationArray = object.getJSONObject("hourly").getJSONArray("precipitation_probability");
                        JSONArray cloudArray = object.getJSONObject("hourly").getJSONArray("cloud_cover");
                        JSONArray windSpeedArray = object.getJSONObject("hourly").getJSONArray("wind_speed_10m");
                        JSONArray snowArray = object.getJSONObject("hourly").getJSONArray("snowfall");
                        for (int i = 0; i < timeArray.length(); i++) {
                            String time = timeArray.getString(i);
                            SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm");
                            SimpleDateFormat outputFormat = new SimpleDateFormat("dd.MM.yyyy HH:mm");
                            Date date = null;
                            try {
                                date = inputFormat.parse(time);
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            String outputString = outputFormat.format(date);
                            String temperature = temperatureArray.getString(i);
                            String humidity = humidityArray.getString(i);
                            double precipitation = precipitationArray.getDouble(i);
                            double cloud = cloudArray.getDouble(i);
                            String windSpeed = windSpeedArray.getString(i);
                            String snowfall = snowArray.getString(i);
                            
                            conditions.add(new Condition(outputString, temperature, humidity, precipitation, cloud, windSpeed, snowfall));
                    }
// Move this outside the loop
runOnUiThread(() -> {
                                RecyclerView rcView = findViewById(R.id.recyclerView2);
                                WeatherAdapter adapter = new WeatherAdapter(conditions);
                                rcView.setLayoutManager(new LinearLayoutManager(WeatherActivity.this, LinearLayoutManager.VERTICAL, false));
                                rcView.setAdapter(adapter);
                            });
                        }
                    catch (JSONException e) {
                        e.printStackTrace();
                    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading