0

Description: In OnRespose method i can see data received from froecast.io in log but when i am passing "response.body().string()" i.e. data from forecast.io as argument(string) to method getCurrentDetails then Method is receiving null and JSONObject is throwing null pointer Exception.

Tried: handle exception through multiple catch block.

    double latitude = -122.423;
    double longitude = 37.8267;
    String apiKey = "cac63237c81f5312b496ed8cce991b40";
    String forecastURL = "https://api.forecast.io/forecast/"+apiKey+"/"+longitude+","+latitude+"";
    if(isNetworkAvailable()) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url(forecastURL).build();

        Call call = client.newCall(request);

        call.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    Log.v(TAG, response.body().string());
                    if (response.isSuccessful()) {
                        mCurrentWeather  = getCurrentDetails(response.body().string());

                    } else {
                        alertUserAboutProblem();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Exception Caught: ", e);
                }
                catch(JSONException e){
                    Log.e(TAG,"Exception Caught: ", e);
                }
            }
        });

        Log.e(TAG, "Program is still running");
    }
    else{
        Toast.makeText(MainActivity.this,"Network_Unavaliable",Toast.LENGTH_LONG).show();
    }



}

private CurrentWeather getCurrentDetails(String string) throws JSONException {

------>>>>> JSONObject jsonObject = new JSONObject(string); String timezone = jsonObject.getString("timezone");

    JSONObject currently =jsonObject.getJSONObject("currently");

    CurrentWeather currentWeather = new CurrentWeather();

    currentWeather.setHumidity(currently.getDouble("humidity"));
    currentWeather.setIcon(currently.getString("icon"));
    currentWeather.setSummary(currently.getString("summary"));
    currentWeather.setTemperature(currently.getDouble("temperature"));
    currentWeather.setTime(currently.getLong("time"));
    currentWeather.setPrecipIntensity(currently.getDouble("percipIntensity"));
    currentWeather.setTimeZone(timezone);

    Toast.makeText(MainActivity.this,String.valueOf(currently.getLong("time")),Toast.LENGTH_LONG).show();
   // Log.d(TAG, String.valueOf(currentWeather.getTime()));
    return currentWeather;
}

private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo coninfo = manager.getActiveNetworkInfo();
    boolean isAvailable = false;
    if(coninfo!=null && coninfo.isConnected()){
        isAvailable = true;
        return isAvailable;
    }

    return false;
}

private void alertUserAboutProblem() {

    AlertDialogFragment dialog =new AlertDialogFragment();
    dialog.show(getFragmentManager(),TAG);
}

}

4
  • so where is your NPE thrown? and what does your JSON look like? Commented Apr 22, 2015 at 1:50
  • Make sure, before you get any value from jsonObject, check json Object is not null and the property that you are trying to read exists, using jsonObject.has("your property"). Other than this, from the data that you have given, I could come only to this conclusion. IF you could print the json value that you are passing, it will be of great help in debugging. Commented Apr 22, 2015 at 2:01
  • NPE is thrown when I am creating JSONObject I have marked that line with arrow. My json is weather data recieving from forecast.io. Commented Apr 22, 2015 at 2:03
  • check whether you are really receiving the response data(json). @Santhana said log your json response. Commented Apr 22, 2015 at 6:00

1 Answer 1

1

Try saving response.body().string() to a String variable and then passing it to getCurrentDetails.

Per the documentation: "the response body is a one-shot value that may be consumed only once".

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.