Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Android

I am getting a fatal exception when I execute my code. Can someone please help me out

05-14 11:04:45.025 2266-2284/com.example.sambhav.stormy E/AndroidRuntime﹕ FATAL EXCEPTION: OkHttp Dispatcher Process: com.example.sambhav.stormy, PID: 2266 java.lang.NullPointerException: Attempt to invoke virtual method 'void com.example.sambhav.stormy.weather.Hour.setSummary(java.lang.String)' on a null object reference at com.example.sambhav.stormy.ui.MainActivity.getHourlyForecast(MainActivity.java:221) at com.example.sambhav.stormy.ui.MainActivity.parseForecastDetails(MainActivity.java:206) at com.example.sambhav.stormy.ui.MainActivity.access$400(MainActivity.java:38) at com.example.sambhav.stormy.ui.MainActivity$2.onResponse(MainActivity.java:115) at com.squareup.okhttp.Call$AsyncCall.execute(Call.java:168) at com.squareup.okhttp.internal.NamedRunnable.run(NamedRunnable.java:33) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) at java.lang.Thread.run(Thread.java:818)

This is the error that I am getting.

public class MainActivity extends ActionBarActivity {

public static final String TAG = MainActivity.class.getSimpleName();

private Forecast mForecast;

@InjectView(R.id.timeLabel) TextView mTimeLabel;
@InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
@InjectView(R.id.humidityValue) TextView mHumidityValue;
@InjectView(R.id.precipValue) TextView mPrecipValue;
@InjectView(R.id.summaryLabel) TextView mSummaryLabel;
@InjectView(R.id.iconImageView) ImageView mIconImageView;
@InjectView(R.id.refreshImageView) ImageView mRefreshImageView;
@InjectView(R.id.progressBar) ProgressBar mProgressBar;

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

    mProgressBar.setVisibility(View.INVISIBLE);

    final double latitude = 37.8267;
    final double longitude = -122.423;

    mRefreshImageView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            getForecast(latitude, longitude);
        }
    });

    getForecast(latitude, longitude);

    Log.d(TAG, "Main UI code is running!");
}

private void getForecast(double latitude, double longitude) {
    String apiKey = "27974c4bc33201748eaf542a6769c3b7";
    String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
            "/" + latitude + "," + longitude;

    if (isNetworkAvailable()) {
        toggleRefresh();

        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) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        toggleRefresh();
                    }
                });
                alertUserAboutError();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        toggleRefresh();
                    }
                });

                try {
                    String jsonData = response.body().string();
                    Log.v(TAG, jsonData);
                    if (response.isSuccessful()) {
                        mForecast = parseForecastDetails(jsonData);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateDisplay();
                            }
                        });
                    } else {
                        alertUserAboutError();
                    }
                }
                catch (IOException e) {
                    Log.e(TAG, "Exception caught: ", e);
                }
                catch (JSONException e) {
                    Log.e(TAG, "Exception caught: ", e);
                }
            }
        });
    }
    else {
        Toast.makeText(this, getString(R.string.network_unavailable_message),
                Toast.LENGTH_LONG).show();
    }
}

private void toggleRefresh() {
    if (mProgressBar.getVisibility() == View.INVISIBLE) {
        mProgressBar.setVisibility(View.VISIBLE);
        mRefreshImageView.setVisibility(View.INVISIBLE);
    }
    else {
        mProgressBar.setVisibility(View.INVISIBLE);
        mRefreshImageView.setVisibility(View.VISIBLE);
    }
}

private void updateDisplay() {
    Current mCurrent = mForecast.getCurrent();
    mTemperatureLabel.setText(mCurrent.getTemperature() + "");
    mTimeLabel.setText("At " + mCurrent.getFormattedTime() + " it will be");
    mHumidityValue.setText(mCurrent.getHumidity() + "");
    mPrecipValue.setText(mCurrent.getPrecipChance() + "%");
    mSummaryLabel.setText(mCurrent.getSummary());

    Drawable drawable = getResources().getDrawable(mCurrent.getIconId());
    mIconImageView.setImageDrawable(drawable);
}

private Current getCurrentDetails(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    Log.i(TAG, "From JSON: " + timezone);

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

    Current current = new Current();
    current.setHumidity(currently.getDouble("humidity"));
    current.setTime(currently.getLong("time"));
    current.setIcon(currently.getString("icon"));
    current.setPrecipChance(currently.getDouble("precipProbability"));
    current.setSummary(currently.getString("summary"));
    current.setTemperature(currently.getDouble("temperature"));
    current.setTimeZone(timezone);

    Log.d(TAG, current.getFormattedTime());

    return current;
}


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

    return isAvailable;
}

private void alertUserAboutError() {
    AlertDialogFragment dialog = new AlertDialogFragment();
    dialog.show(getFragmentManager(), "error_dialog");
}

private Forecast parseForecastDetails(String jsonData) throws JSONException {
    Forecast forecast = new Forecast();
    forecast.setCurrent(getCurrentDetails(jsonData));
    forecast.setHourlyForecast(getHourlyForecast(jsonData));
    forecast.setDailyForecast(getDailyForecast(jsonData));
    return forecast;
}

private Hour[] getHourlyForecast(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    JSONObject hourly = forecast.getJSONObject("hourly");
    JSONArray data = hourly.getJSONArray("data");

    Hour hours[] = new Hour[data.length()];

    for(int i=0;i<data.length();i++) {
        JSONObject jsonHour = data.getJSONObject(i);
        hours[i].setSummary(jsonHour.getString("summary"));
        hours[i].setTimeZone(timezone);
        hours[i].setTime(jsonHour.getLong("time"));
        hours[i].setTemperature(jsonHour.getDouble("temperature"));
        hours[i].setIcon(jsonHour.getString("icon"));
    }

    return hours;
}

private Day[] getDailyForecast(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    JSONObject daily = forecast.getJSONObject("daily");
    JSONArray data = daily.getJSONArray("data");

    Day days[] = new Day[data.length()];

    for(int i=0;i<data.length();i++) {
        JSONObject jsonDay = data.getJSONObject(i);

        days[i].setSummary(jsonDay.getString("summary"));
        days[i].setTimeZone(timezone);
        days[i].setTime(jsonDay.getLong("time"));
        days[i].setIcon(jsonDay.getString("icon"));
        days[i].setTemperatureMax(jsonDay.getDouble("temperatureMax"));
    }
    return days;

}

}

1 Answer

Hi Sambhav,

Your problem:

private Hour[] getHourlyForecast(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    JSONObject hourly = forecast.getJSONObject("hourly");
    JSONArray data = hourly.getJSONArray("data");

    Hour hours[] = new Hour[data.length()];

    for(int i=0;i<data.length();i++) {
        JSONObject jsonHour = data.getJSONObject(i);
        hours[i].setSummary(jsonHour.getString("summary"));
        hours[i].setTimeZone(timezone);
        hours[i].setTime(jsonHour.getLong("time"));
        hours[i].setTemperature(jsonHour.getDouble("temperature"));
        hours[i].setIcon(jsonHour.getString("icon"));
    }

    return hours;
}

you're instantiating an array of null(empty array) with length equal data.length, so you'll have something like this {null,null,null........} and if you try hours[0].setSummary(jsonHour.getString("summary")); then what you're actually doing is null.setSummary(jsonHour.getString("summary")); which will result in a null pointer exception.

Your Solution:

private Hour[] getHourlyForecast(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);
    String timezone = forecast.getString("timezone");
    JSONObject hourly = forecast.getJSONObject("hourly");
    JSONArray data = hourly.getJSONArray("data");

    Hour hours[] = new Hour[data.length()];

    for(int i=0;i<data.length();i++) {
        JSONObject jsonHour = data.getJSONObject(i);
        hours[i] = new Hour();
        hours[i].setSummary(jsonHour.getString("summary"));
        hours[i].setTimeZone(timezone);
        hours[i].setTime(jsonHour.getLong("time"));
        hours[i].setTemperature(jsonHour.getDouble("temperature"));
        hours[i].setIcon(jsonHour.getString("icon"));
    }

    return hours;
}

This way you'll initialize hours[i] to an object of type Hour. Hope this helped! If something is still confusing please ask again. also, check out this which is the same problem you're facing.

Good luck ! :-)