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

Mirosław Mitura
Mirosław Mitura
3,294 Points

FATAL EXCEPTION: OkHttp Dispatcher

Hi! I've got this issue with FATAL EXCEPTION: OkHttp Dispatcher and null object reference ... Everything was fine until constructor CurrentWeather appeared ...

Thank's in advance for any help .

LOGCAT : 07-10 21:50:48.877 4625-4687/miroslaw.mitura.strormy E/AndroidRuntime: FATAL EXCEPTION: OkHttp Dispatcher Process: miroslaw.mitura.strormy, PID: 4625 java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String miroslaw.mitura.strormy.CurrentWeather.getLocationLabel()' on a null object reference at miroslaw.mitura.strormy.MainActivity$1.onResponse(MainActivity.java:74) at okhttp3.RealCall$AsyncCall.run(RealCall.kt:138) at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113) at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588) at java.lang.Thread.run(Thread.java:818)

public class MainActivity extends AppCompatActivity {

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

private CurrentWeather currentWeather;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ActivityMainBinding binding = DataBindingUtil.setContentView(MainActivity.this,
            R.layout.activity_main);

    String apiKey = "xxx";
    double latitude = 54.6052800;
    double longitude = 18.3471700;
    String forecastURL = "https://weatherbit-v1-mashape.p.rapidapi.com/current?lat="+ latitude+"&lon="+longitude;

    if(isNetworkAvailable()) {
        OkHttpClient client = new OkHttpClient();

        Request request = new Request.Builder()
                .url(forecastURL)
                .get()
                .addHeader("x-rapidapi-key", apiKey)
                .addHeader("x-rapidapi-host", "weatherbit-v1-mashape.p.rapidapi.com")
                .build();


        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {

            }


            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                try {
                    String jsonData = response.body().string();

                    if (response.isSuccessful()) {

                        currentWeather = getCurrentDetails(jsonData);

                        CurrentWeather displayWeather = new CurrentWeather(
                                currentWeather.getLocationLabel(),
                                currentWeather.getIcon(),
                                currentWeather.getTime(),
                                currentWeather.getTemperature(),
                                currentWeather.getHumidity(),
                                currentWeather.getPrecipChance(),
                                currentWeather.getTimezone()
                        );

                        binding.setWeather(displayWeather);

                    } else {
                        alertUserAboutError();
                    }

                } catch (IOException e) {
                    Log.e(TAG, "IO Exception caught: ", e);
                } catch (JSONException e) {
                    Log.e(TAG,"JSON Exception caught: ",e);
                }
            }
        });
    }
    Log.d(TAG,"Main UI code is running, horray!");
}

public CurrentWeather getCurrentDetails(String jsonData) throws JSONException {
    JSONObject forecast = new JSONObject(jsonData);

    String timezone;

    JSONArray data = forecast.getJSONArray("data");
    for (int i = 0; i< data.length(); i++) {
        JSONObject weatherData = data.getJSONObject(i);

        timezone = weatherData.getString("timezone");
        Log.i(TAG,"From JSON:" + timezone);

        CurrentWeather currentWeather = new CurrentWeather();
        currentWeather.setHumidity(weatherData.getDouble("rh"));

        String icon = weatherData.getJSONObject("weather").getString("icon");
        currentWeather.setIcon(icon);
        Log.i(TAG,"From JSON:" + icon );

        String location = (weatherData.getString("city_name"));
        currentWeather.setLocationLabel(location);
        Log.i(TAG,"From JSON:" + location);

        currentWeather.setPrecipChance(weatherData.getDouble("precip"));
        currentWeather.setTemperature(weatherData.getDouble("temp"));
        currentWeather.setTimezone(timezone);


        Log.d(TAG,currentWeather.getFormattedTime());
    }
    return null;



}



private boolean isNetworkAvailable() {
    ConnectivityManager manager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo networkInfo = manager.getActiveNetworkInfo();
    boolean isAvailable = false;
    if(networkInfo != null && networkInfo.isConnected()){
        isAvailable = true;
    }
    else {
        Toast.makeText(this, R.string.network_is_not_available,
                Toast.LENGTH_LONG).show();
    }
return isAvailable;
}

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

}