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

In Stormy app , writting the code for getting data using jsonObject , I am getting a fatal exception:okHttp dispatcher

when i am trying to get the data using currentweather object i am getting this error...... what should i do...please help asap

package com.example.omi.stormy;

import android.app.Activity; import android.content.Context; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.util.Log; import android.widget.Toast;

import com.squareup.okhttp.Call; import com.squareup.okhttp.Callback; import com.squareup.okhttp.OkHttpClient; import com.squareup.okhttp.Request; import com.squareup.okhttp.Response;

import org.json.JSONException; import org.json.JSONObject;

import java.io.IOException;

public class MainActivity extends Activity {

public static final String TAG = MainActivity.class.getSimpleName();
public CurrentWeather mCurrentWeather;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);


    String apiKey="d05001534ac371b98079837b70b90eeb";
    double latitude=37.8267;
    double longitude=-122.423;

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

    final 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 {

                if (response.isSuccessful()) {
                    String jsonData=response.body().string();
                    Log.v(TAG, jsonData);
                    mCurrentWeather=getCurrentDetails(jsonData);

                } 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();
    }

    Log.d(TAG, "MainACtivity Successfully run");



}

private CurrentWeather 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");

    CurrentWeather currentWeather=new CurrentWeather();
    currentWeather.setHumidity(currently.getDouble("humidity"));
    currentWeather.setTime(currently.getLong("time"));
    currentWeather.setIcon(currently.getString("icon"));
    currentWeather.setPrecipChance(currently.getDouble("precipProbability"));
    currentWeather.setTemperature(currently.getDouble("temperature"));

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


    return currentWeather;
}

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");

}

}

E/AndroidRuntime﹕ FATAL EXCEPTION: OkHttp Dispatcher Process: com.example.omi.stormy, PID: 21384 java.lang.NullPointerException: id == null at java.util.TimeZone.getTimeZone(TimeZone.java:349) at com.example.omi.stormy.CurrentWeather.getFormattedTime(CurrentWeather.java:53) at com.example.omi.stormy.MainActivity.getCurrentDetails(MainActivity.java:99) at com.example.omi.stormy.MainActivity.access$000(MainActivity.java:23) at com.example.omi.stormy.MainActivity$1.onResponse(MainActivity.java:56) 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)

1 Answer

From the stack trace you're getting a null pointer exception when you try to look up the timezone in the getFormattedTime() method of CurrentWeather. It looks like you're pulling the timezone out of the JSON data but forgetting to store it in your CurrentWeather object.