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 Build a Weather App (2015) Hooking Up the Model to the View Plugging in the Data

Marcelo Moyano
PLUS
Marcelo Moyano
Courses Plus Student 13,610 Points

Attempt to invoke virtual method on a null object reference. Plugging in the data | Build a weather app

Well, this is my 2nd time doing the Build a weather app course. And its the 1st time that it is giving me a hard time with this exception that is jumping in when I try to update the display.

This is what my code looks like:

public class MainActivity extends ActionBarActivity {

public static final String TAG = MainActivity.class.getSimpleName();
private CurrentWeather mCurrentWeather;
@InjectView(R.id.timeLabel) TextView mTimeLabel;
@InjectView(R.id.temperatureLabel) TextView mTemperatureLabel;
@InjectView(R.id.locationLabel) TextView mLocationLabel;
@InjectView(R.id.humidityValue) TextView mHumidityValue;
@InjectView(R.id.precipValue) TextView mPrecipValue;
@InjectView(R.id.summaryLabel) TextView mSummaryLabel;
@InjectView(R.id.iconImageView) ImageView mIconImageView;






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



    double latitude = -31.4299;
    double longitude = -64.1855;
    String apiKey = "adb44e9f6fec19f4fbf0c137a087c498";
    String forecastUrl = "https://api.forecast.io/forecast/" + apiKey +
            "/" + latitude + "," + longitude;
    if (isNetworkAvailable()) {
        OkHttpClient client = new OkHttpClient();
        Request solicitud = new Request.Builder()
                .url(forecastUrl)
                .build();
        Call llamada = client.newCall(solicitud);
        llamada.enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                try {
                    String jsonData = response.body().string();
                    if (response.isSuccessful()) {
                        mCurrentWeather = getCurrentdetails(jsonData);
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                updateDisplay();
                            }
                        });

                    } else {
                        alertarUsuarioSobreError();
                    }
                } catch (IOException e) {
                    Log.e(TAG, "Se ha encontrado un error", e);
                } catch (JSONException e){
                    Log.e(TAG, "Se ha encontrado un error", e);
                }
            }
        });
    } else{
        Toast.makeText(this, getString(R.string.error_conectividad_mensaje), Toast.LENGTH_LONG).show();
    }

This is my updateDisplay() method:

private void updateDisplay() {
        mTemperatureLabel.setText(mCurrentWeather.getTemperature());
} 

And my error log goes like this:

    03-09 11:26:07.256    2495-2495/com.mindsmack.climazo E/AndroidRuntime﹕ FATAL EXCEPTION: main
    Process: com.mindsmack.climazo, PID: 2495
    java.lang.NullPointerException: Attempt to invoke virtual method 'int com.mindsmack.climazo.CurrentWeather.getTemperature()' on a null object reference
            at com.mindsmack.climazo.MainActivity.updateDisplay(MainActivity.java:107)
            at com.mindsmack.climazo.MainActivity.access$200(MainActivity.java:32)
            at com.mindsmack.climazo.MainActivity$1$1.run(MainActivity.java:84)
            at android.os.Handler.handleCallback(Handler.java:739)
            at android.os.Handler.dispatchMessage(Handler.java:95)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

I have already done the debugging process, adding a breakpoint just after the Views are inserted and this is what i got:

'''mHumidityValue =  android.widget.TextView{385572bf V.ED.... ......ID 0,0-0,0 #7f090046 app:id/humidityValue}

mIconImageView = android.widget.ImageView{4123d8c V.ED.... ......I. 0,0-0,0 #7f090043 app:id/iconImageView}

mPrecipValue = android.widget.TextView{2f58cea V.ED.... ......ID 0,0-0,0 #7f090048 app:id/precipValue}

mSummaryLabel = android.widget.TextView{3a787bdb V.ED.... ......ID 0,0-0,0 #7f090049 app:id/summaryLabel}

mTemperatureLabel = android.widget.TextView{16ba678 V.ED.... ......ID 0,0-0,0 #7f09003f app:id/temperatureLabel}'''

Seems like every View has its corresponding Value, but that exception is still appearing.

Thanks in advance!

3 Answers

Josh Gold
Josh Gold
12,207 Points

The problem might be that the setText method requires a string, but your getTemperature method returns either an int or a double (depending on your implementation). To work around this problem, you can either cast the get temperature method in that line to a String, or you can concatenate the result with an empty string like this:

 mTempuratureLabel.setText(mCurrentWeather.getTemperature() + "");
Marcelo Moyano
Marcelo Moyano
Courses Plus Student 13,610 Points

Josh, Thanks for answering. My error log pointed out that I was referencing a null Object. I tried to inject the Views in different places inside my code but it seemed like they weren't being injected at all, I also did try to put them myself by calling findViewById(); But it neither worked. So I just copied the whole project and started a new one, and this time it worked perfectly.

what::

Marcelo Moyano
Marcelo Moyano
Courses Plus Student 13,610 Points

I have just updated some changes to the answer, It wasn't quite well formatted. Please let me know what doubts you have about this question, I would really love to get to know where is my problem and find a solution to it.

Same issue :(