AsyncTask doInBackground to return multiple strings Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of AsyncTask doInBackground to return multiple strings without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m trying to build a very basic weather app in android studio. I am using AsyncClass to return multiple strings.

As you can see in the code, I used a class named “Wrapper” that is used to store my strings so I can just return a class object and use it in the onPostExecute method of the AsyncTask. The problem I am facing is that when I test the app, all of the returned Strings somehow are undefined (the default for the Wrapper class). This means the strings are not being updated in the doInBackground method and I can’t seem to figure out why!

My Activity

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        Log.i(MainActivity.class.getSimpleName(), "Can't connect to Google Play Services!");
    }
    private class Wrapper
    {
          String Temperature = "UNDEFINED";
         String city = "UNDEFINED";
         String country = "UNDEFINED";
    }

    private class GetWeatherTask extends AsyncTask<String, Void, Wrapper> {
        private TextView textView;

        public GetWeatherTask(TextView textView) {
            this.textView = textView;
        }

        @Override
        protected Wrapper doInBackground(String... strings) {
            Wrapper w = new Wrapper();
            String Temperature = "x";
            String city = "y";
            String country = "z";

            try {
                URL url = new URL(strings[0]);
                HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();

                InputStream stream = new BufferedInputStream(urlConnection.getInputStream());
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
                StringBuilder builder = new StringBuilder();

                String inputString;
                while ((inputString = bufferedReader.readLine()) != null) {
                    builder.append(inputString);
                }

                JSONObject topLevel = new JSONObject(builder.toString());
                JSONObject main = topLevel.getJSONObject("main");
                JSONObject cityobj = topLevel.getJSONObject("city");
                Temperature = String.valueOf(main.getDouble("temp"));
                city = cityobj.getString("name");
               country = cityobj.getString("country");

                w.Temperature= Temperature;
                w.city= city;
                w.country=country;

                urlConnection.disconnect();
            } catch (IOException | JSONException e) {
                e.printStackTrace();
            }
            return w;
        }

        @Override
        protected void onPostExecute(Wrapper w) {
            textView.setText("Current Temperature: " + w.Temperature + " C" + (char) 0x00B0
                       +"n" + "Current Location: "+ w.country +"n" + "City: "+  w.city );
        }
    }
}

UPDATE:

turned out that that I was using the wrong url in my code,I was using : http://api.openweathermap.org/data/2.5/weather?lat=%f&lon=%f&units=%s&appid=%s

Instead I should’ve been using:

http://api.openweathermap.org/data/2.5/forecast?lat=%f&lon=%f&units=%s&appid=%s

-aka instead of weather I should’ve been using forcast

Answer

Your error starts here

JSONObject main = topLevel.getJSONObject("main");

Probably because the topLevel object has no "main" key.

{  
   "city":{  },
   "cod":"200",
   "message":0.1859,
   "cnt":40,
   "list":[  ]
}

Throw your JSON into here. https://jsonformatter.curiousconcept.com/

You’ll notice that there are many, many "main" keys that are within the "list" element, but you have to parse those starting from getJSONArray("list").


Basically, something like this

String city = "undefined";
String country = "undefined";
List<Double> temperatures = new ArrayList<Double>();

try {
    JSONObject object = new JSONObject(builder.toString());
    JSONObject jCity = object.getJSONObject("city");
    city = jCity.getString("name");
    country = jCity.getString("country");

    JSONArray weatherList = object.getJSONArray("list");
    for (int i = 0; i < weatherList.length(); i++) {
        JSONObject listObject = weatherList.getJSONObject(i);
        double temp = listObject.getJSONObject("main").getDouble("temp");
        temperatures.add(temp);
    }

} catch (JSONException e) {
    e.printStackTrace();
}

return new Wrapper(city, country, temperatures);
We are here to answer your question about AsyncTask doInBackground to return multiple strings - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji