0

The following is the code for finding weather by entering the city name or place name.. the result is a string from the doInBackground method ... but unfortunately its returning null...

@Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if(result == null){
            Toast.makeText(MainActivity.this,"Place not found",Toast.LENGTH_LONG).show();
        }
        else{
            try {

                String message = "";

                JSONObject jsonObject = new JSONObject(result);

                String weatherInfo = jsonObject.getString("weather");

                Log.i("Weather content", weatherInfo);

                JSONArray arr = new JSONArray(weatherInfo);

                for (int i = 0; i < arr.length(); i++) {

                    JSONObject jsonPart = arr.getJSONObject(i);

                    String main = "";
                    String description = "";

                    main = jsonPart.getString("main");
                    description = jsonPart.getString("description");

                    if (main != "" && description != "") {

                        message += main + ": " + description + "\r\n";

                    }

                }

                if (message != "") {

                    weatherReport.setText(message);

                } else {

                    Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show();

                }


            } catch (JSONException e) {

                Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show();

            }

The doInBackground() method..

protected String doInBackground(String... urls) {

        String result = "";
        URL url;
        HttpURLConnection httpURLConnection;

        try {
            url = new URL(urls[0]);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            InputStream in = httpURLConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(in);
            int data = reader.read();
            while(data != -1){
                char current = (char) data;
                result += current;

                data = reader.read();
            }
            return result;

        }
        //combined the exceptions MalformedURL and IOException to a common to display a toast msg
        catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }

The download url ..DownloadTask is the name of the class which extends from AsyncTask<> and has methods doInBackground and onPostExecute().. pls help me as to why the result String is returning null..

weather.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            try {

                //to hide the keyboard after pressing the button
                InputMethodManager manager =
                        (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                manager.hideSoftInputFromInputMethod(weatherInput.getWindowToken(),0);

                DownloadTask downloadTask = new DownloadTask();

                //used to encode the entered input for url.. for example San Fransisco appears in url
                //as San%20Fransisco ... and to enable that we use the encoder...
                String encodedCity = URLEncoder.encode(city,"UTF-8");

                downloadTask.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCity +
                        "&appid=cd66504ca815ddc1971662a9f2147f84\n");

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

        }
    });
  • did you check the response from the interface its "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info." – zombie Mar 02 '17 at 02:57
  • Well... You did `return null;`, **and** you print an exception, so maybe check the logcat – OneCricketeer Mar 02 '17 at 02:58
  • Also, `main != ""` is **not** [How to compare strings in Java](http://stackoverflow.com/questions/513832/how-do-i-compare-strings-in-java) – OneCricketeer Mar 02 '17 at 02:59

2 Answers2

0

Please test your API before writing any Java code.


You have a trailing \n in your URL.

Just open up the actual URL in your code, or cURL it...

curl 'http://api.openweathermap.org/data/2.5/weather?q=San%20Antonio&appid=cd66504ca815ddc1971662a9f2147f84\n' | jq 

{
  "cod": 401,
  "message": "Invalid API key. Please see http://openweathermap.org/faq#error401 for more info."
}

Remove the \n at the end

{
  "coord": {
    "lon": -98.49,
    "lat": 29.42
  },
  "weather": [
    {
      "id": 800,
      "main": "Clear",
      "description": "clear sky",
      "icon": "01n"
    }
  ],
  "base": "stations",
  "main": {
    "temp": 288.15,
    "pressure": 1023,
    "humidity": 27,
    "temp_min": 285.15,
    "temp_max": 291.15
  },
  "visibility": 16093,
  "wind": {
    "speed": 3.6,
    "deg": 30
  },
  "clouds": {
    "all": 1
  },
  "dt": 1488423180,
  "sys": {
    "type": 1,
    "id": 2713,
    "message": 0.0075,
    "country": "US",
    "sunrise": 1488459476,
    "sunset": 1488501264
  },
  "id": 4726206,
  "name": "San Antonio",
  "cod": 200
}
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
  • I removed the \n at the end and still i am getting the same error that is its showing a toast Message that says Place not Found..pls explain – Hemant Joshi Mar 02 '17 at 14:16
  • Your parsing can still throw an exception. Please try using Volley https://developer.android.com/training/volley/request.html#request-json – OneCricketeer Mar 02 '17 at 15:33
0

I found few issues on your code. Try this.

String message = ""; 
JSONObject jsonObject = new JSONObject(result); 
JSONArray arr = jsonObject.optJSONArray("weather"); 
for (int i = 0; i < arr.length(); i++) { 
    JSONObject jsonPart = arr.optJSONObject(i); 
    String main = jsonPart.optString("main");
    String description = jsonPart.optString("description"); 
    if (!TextUtils.isEmpty(main) && !TextUtils.isEmpty(description)) { 
        message += main + ": " + description + "\r\n"; 
     } 
 } 
 if (!TextUtils.isEmpty(message)) { 
       weatherReport.setText(message); 
  } else { 
      Toast.makeText(getApplicationContext(), "Could not find weather", Toast.LENGTH_LONG).show(); 
     }
albeee
  • 1,452
  • 1
  • 12
  • 20
  • I changed the code and still i am getting the same error that is its showing a toast Message that says Place not Found..pls explain – Hemant Joshi Mar 02 '17 at 14:16
  • Seems you're getting some exception - What was that? 1. Add a INTERNET_PERMISSION in your android manifest file 2. Check the exception and resolve it. 3. I think, the reading stream code may not be perfect. – albeee Mar 02 '17 at 14:35
  • so use this. InputStreamReader reader = new InputStreamReader(in); BufferedReader buffReader = new BufferedReader(reader); String readLine; StringBuffer stringBuffer = new StringBuffer(); while ((readLine = buffReader.readLine()) != null) { stringBuffer.append(readLine).append("\n"); } result = sb.toString(); reader.close(); in.close(); – albeee Mar 02 '17 at 14:35
  • Yeah i copied ur code and also removed \n at the end and uninstalled the app and reinstalled it and now its working.. but i dont get it what was the problem.. apart from the url which i changed many times during my app development? – Hemant Joshi Mar 02 '17 at 16:25
  • Just do the debugging. That always helps to find the problem in the first place. – albeee Mar 02 '17 at 16:38
  • No its working and i dont know why..what is the difference between optString and getString – Hemant Joshi Mar 02 '17 at 16:44
  • I guess the one you have written for reading data from input stream may have problem. Maybe you can try debugging that why it was failing. In the meantime time, vote me up. ;-) – albeee Mar 02 '17 at 16:46