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

Null pointer exception in java

I am getting the following error in the code

java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference.

 at com.example.hemanth.stromy.MainActivity.updateDisplay(MainActivity.java:96)
        at com.example.hemanth.stromy.MainActivity.access$200(MainActivity.java:31)
        at com.example.hemanth.stromy.MainActivity$1$1.run(MainActivity.java:72)
package com.example.hemanth.stromy;

import android.app.AlertDialog;
import android.app.DownloadManager;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.TextView;
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;

import butterknife.InjectView;


public class MainActivity extends ActionBarActivity {

   private CurrentWeather mcurrentweather;
   public static final String TAG = MainActivity.class.getSimpleName();
    @InjectView(R.id.temperatureLabel)TextView mTemperatureLabel;
    @InjectView(R.id.humidityValue) TextView mHumiditylable;
    @InjectView(R.id.precipValue) TextView mPreciplable;
    @InjectView(R.id.summaryLabel) TextView mSummaryLabel;
    @InjectView(R.id.timelabel)TextView mTimeLabel;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String apiKey = "2b345aa7cb761cc607bce49e23e4cb72";
        double latitude = 37.8267;
        double longitude = -122.423;
        String apiUrl = "https://api.forecast.io/forecast/"+apiKey+"/"+latitude+","+longitude;
        if(isNetworkAvailable()) {
            OkHttpClient Client = new OkHttpClient();
            Request request = new Request.Builder().url(apiUrl).build();
            Call call = Client.newCall(request);
            call.enqueue(new Callback() {
                @Override
                public void onFailure(Request request, IOException e) {
                    Toast.makeText(MainActivity.this,"There are network problems",Toast.LENGTH_LONG);
                }

                @Override
                public void onResponse(Response response) {

                    try {

                        String jasonData = response.body().string();
                        if (response.isSuccessful()) {
                            Log.v(TAG,jasonData);
                            mcurrentweather = getCurrentDetails(jasonData);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    updateDisplay();
                                }
                            });


                        } else {
                            alertUser();
                        }
                    }
                    catch (IOException e) {
                        Log.e(TAG, "expection is ", e);
                    }
                    catch (JSONException e){
                        Log.e(TAG, "expection is ", e);
                    }
                }
            });
        }
        else{
            Toast.makeText(this,"The network is unavailable",Toast.LENGTH_LONG).show();
        }
    }

    private void updateDisplay() {
        mTemperatureLabel.setText(mcurrentweather.getmTemeperature()+"");
        mTimeLabel.setText("At "+mcurrentweather.getFormattedString()+" it will be ");
        mHumiditylable.setText(mcurrentweather.getmHumidity()+"");
        mPreciplable.setText(mcurrentweather.getmPrecipChance() + "");
        mSummaryLabel.setText(mcurrentweather.getmSummary());



    }

    private CurrentWeather getCurrentDetails(String jasonData) throws JSONException{
        JSONObject forecast = new JSONObject(jasonData);
        String timezone = forecast.getString("timezone");
        JSONObject current = forecast.getJSONObject("currently");
        CurrentWeather currentWeather = new CurrentWeather();
        currentWeather.setmHumidity(current.getDouble("humidity"));
        currentWeather.setmTemeperature(current.getDouble("temperature"));
        currentWeather.setmTimeZone(timezone);
        currentWeather.setMtime(current.getInt("time"));
        Log.i(TAG,"From Json : "+timezone);

        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 alertUser() {
        AlertDialogFragment dialog = new AlertDialogFragment();
        dialog.show(getFragmentManager(),"Error_dialog");

    }


}

2 Answers

The problem is the mTemperatureLabel.setText(text). The variable mTemperatureLabel is probably null and you call the setText method on that null, which you can't.

I guess that the problem is on the findViewById from InjectView, but its not here, so i cant tell more, without XML code.

Thanks for reply..

Here is the xml code.. Yes the problem is with mTemperatureLabel being a null and i am invoking the setText method using NULL. I found it by debugging. But i have no idea how to fix it. Please help me to fix it.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"
    android:background="#ffffc32f"
    android:id="@+id/MainActivity"
    android:focusableInTouchMode="false">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="100"
        android:id="@+id/temperatureLabel"
        android:textSize="130sp"
        android:textIsSelectable="true"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/degree"
        android:layout_alignTop="@+id/temperatureLabel"
        android:layout_toRightOf="@+id/temperatureLabel"
        android:layout_toEndOf="@+id/temperatureLabel"
        android:src="@drawable/degree" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Temperature at 5 pm"
        android:id="@+id/timelabel"
        android:textColor="#80ffffff"
        android:textSize="20sp"
        android:layout_above="@+id/temperatureLabel"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="42dp" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Durgapur West Bengal"
        android:id="@+id/tagline"
        android:textColor="@android:color/white"
        android:textSize="18sp"
        android:layout_alignParentTop="true"
        android:layout_alignLeft="@+id/timelabel"
        android:layout_alignStart="@+id/timelabel"
        android:layout_marginTop="58dp" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/iconImageView"
        android:src="@drawable/cloudy"
        android:cropToPadding="false"
        android:layout_alignBottom="@+id/tagline"
        android:layout_toLeftOf="@+id/temperatureLabel"
        android:layout_toStartOf="@+id/temperatureLabel" />

    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/temperatureLabel"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
        android:weightSum="100"
        android:id="@+id/linearLayout">

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="50">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="HUMIDITY"
                android:id="@+id/humidity"
                android:textColor="#80ffffff"
                android:textSize="20sp"
                android:gravity="center_horizontal" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="0.98"
                android:id="@+id/humidityValue"
                android:textSize="32sp"
                android:gravity="center_horizontal" />

        </LinearLayout>

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:layout_weight="50">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="Precepitation"
                android:id="@+id/precipitaion"
                android:textSize="20sp"
                android:textColor="#80ffffff"
                android:gravity="center_horizontal" />

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="100%"
                android:id="@+id/precipValue"
                android:textSize="30sp"
                android:gravity="center_horizontal" />
        </LinearLayout>
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="the day is stromy"
        android:id="@+id/summaryLabel"
        android:textColor="#80ffffff"
        android:textSize="25sp"
        android:layout_below="@+id/linearLayout"
        android:layout_alignLeft="@+id/timelabel"
        android:layout_alignStart="@+id/timelabel"
        android:layout_marginTop="44dp" />

</RelativeLayout>

XML Code looks fine with me, Does the method getmTemeperature() in CurrentWeather class return null ?

I found the prob. I forgot to add

ButterKnife.inject(this); in the code.

Thanks for reply.