0

I am trying to use openweathermap to get basic data about weather and paste it into textview, but strings to which I am getting data doesn't refresh texts in textviews.

Code:

 @SuppressLint("StaticFieldLeak")
    class DownloadJSON extends AsyncTask<String, Void, String> {

        @Override
        protected String doInBackground(String... strings) {

            URL url;
            HttpURLConnection httpURLConnection;
            InputStream inputStream;
            InputStreamReader inputStreamReader;
            StringBuilder result = new StringBuilder();
            try {
                url = new URL(strings[0]);
                httpURLConnection = (HttpURLConnection) url.openConnection();
                inputStream = httpURLConnection.getInputStream();
                inputStreamReader = new InputStreamReader(inputStream);
                int data = inputStreamReader.read();
                while (data != -1) {
                    result.append((char) data);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            return result.toString();
        }

    }
    txtCity = findViewById(R.id.txtCity);
    txtTemp = findViewById(R.id.txtTemp);

    DownloadJSON downloadJSON = new DownloadJSON();

    try {
        String result = downloadJSON.execute(url).get();
        JSONObject jsonObject = new JSONObject(result);
        String temp = jsonObject.getJSONObject("main").getString("temp");
        String feel_like = jsonObject.getJSONObject("main").getString("feels_like");

        txtCity.setText(City);
        txtValueFeelLike.setText(feel_like);
        txtTemp.setText(temp);
    } catch (ExecutionException | InterruptedException | JSONException e) {
        e.printStackTrace();
    }
}

'''

  String City = "Warsaw";
String url = "http://api.openweathermap.org/data/2.5/weather?q="+City+"&units=metric&appid=eace0bd8251cf6ab043ab9858b796256";
   TextView txtCity, txtValueFeelLike, txtTemp;

What am I doing wrong?

Ok, I made a change, tried to make it from the scratch again, but now with onPostExecute(). Still nothing...

public class Weather {

private static final String OPEN_WEATHER_MAP_URL =
        "http://api.openweathermap.org/data/2.5/weather?q=Warsaw&units=metric&appid=eace9b6857889076855263cfdb5707c0d00";

public interface AsyncResponse {

    void processFinish(String output1, String output2, String output3, String output4, String output5, String output6);
}

public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {

    public AsyncResponse delegate = null;//Call back interface

    @Override
    protected JSONObject doInBackground(String... params) {

        JSONObject jsonWeather = null;
        try {
            jsonWeather = getWeatherJSON();
        } catch (Exception e) {
            Log.d("Error", "Cannot process JSON results", e);
        }


        return jsonWeather;
    }

    @Override
    public void onPostExecute(JSONObject json) {
        try {
            if(json != null){
                JSONObject details = json.getJSONArray("weather").getJSONObject(0);
                JSONObject main = json.getJSONObject("main");
                DateFormat df = DateFormat.getDateTimeInstance();


                String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
                String description = details.getString("description").toUpperCase(Locale.US);
                @SuppressLint("DefaultLocale") String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
                String humidity = main.getString("humidity") + "%";
                String pressure = main.getString("pressure") + " hPa";
                String updatedOn = df.format(new Date(json.getLong("dt")*1000));

                delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn);

            }
        } catch (JSONException e) {
            
        }

    }
}

public static JSONObject getWeatherJSON() {
    try {
        URL url = new URL(OPEN_WEATHER_MAP_URL);
        HttpURLConnection connection =
                (HttpURLConnection) url.openConnection();

        BufferedReader reader = new BufferedReader(
                new InputStreamReader(connection.getInputStream()));

        StringBuilder json = new StringBuilder(1024);
        String tmp = "";
        while ((tmp = reader.readLine()) != null)
            json.append(tmp).append("\n");
        reader.close();

        JSONObject data = new JSONObject(json.toString());

        // This value will be 404 if the request was not
        // successful
        if (data.getInt("cod") != 200) {
            return null;
        }

        return data;
    } catch (Exception e) {
        return null;
    }
}}

And Main Activity:

 @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    cityField = (TextView) findViewById(R.id.city_field);
    updatedField = (TextView) findViewById(R.id.updated_field);
    detailsField = (TextView) findViewById(R.id.details_field);
    currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
    humidity_field = (TextView) findViewById(R.id.humidity_field);
    pressure_field = (TextView) findViewById(R.id.pressure_field);

    Weather.placeIdTask asyncTask = new Weather.placeIdTask() {
        public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn) {
            cityField.setText(weather_city);
            updatedField.setText(weather_updatedOn);
            detailsField.setText(weather_description);
            currentTemperatureField.setText(weather_temperature);
            humidity_field.setText("Humidity: " + weather_humidity);
            pressure_field.setText("Pressure: " + weather_pressure);

        }
    };

No idea what to do now.

Milo
  • 11
  • 1
  • An `AsyncTask` is asynchronous - you cannot call `execute` and immediately get the result (it runs in the background). Take a look [here](https://stackoverflow.com/questions/12575068/how-to-get-the-result-of-onpostexecute-to-main-activity-because-asynctask-is-a) for some solutions for how to get the result from an AsyncTask and use it somewhere using an interface. You could also just set them in `onPostExecute()` in your AsyncTask. – Tyler V Mar 28 '22 at 02:20
  • Thank you. Ok, I made a second try. I edited my question with my new solution which... still doesn't work.. I have used onPostExecute, but still nothing. – Milo Mar 28 '22 at 19:25
  • You never call `execute`... You should add `asyncTask.execute();` in there after you create it to actually make it run. – Tyler V Mar 29 '22 at 01:03
  • I'm trying to follow your advices, but still can't do it work.. Can you tell me a little more about how should i implement it? – Milo Mar 29 '22 at 20:01
  • Literally just type `asyncTask.execute(url);` at the end of your `onCreate()` method. You create the AsyncTask object but never execute it. If you can't get that to work I suggest reading some tutorials about [AsyncTask](https://developer.android.com/reference/android/os/AsyncTask) and making an extremely simple example case that just prints things to start with to help you learn. StackOverflow is not a debugger - you have to learn to do that yourself. – Tyler V Mar 29 '22 at 20:42

0 Answers0