Android: How to fix “null object reference” error (with code)


This post is specifically for a problem whose solution is usually hard to find (at least now). The solution is at the end.

Basically, the problem lies in the referencing method being used to make reference towards the current activity. The solution is to make the referencing dynamic. Read below for solution with code example.

Problem

  1. You are developing an android app.
  2. You have loaded a fragment.
  3. You are taking inputs from EditText and calculating.
  4. Moreover, you are showing the result in a TextView.

Basically, it looks like this,

Now, when the fragment is loaded and you fill in the values and press the button, you get this error in Logcat

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

As evident from my Logcat as well.

 

Problematic code is given below:

/**
 * Created by Codeonion on 9/26/2015.
 */
public class CustomFragmentClass extends Fragment implements View.OnClickListener{
    TextView mFirstNumber;
    EditText mSecondNumber;
    TextView m_resultHolder;
    Button btnAdd;
    double num1, num2, result;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View fragmentHandle = inflater.inflate(R.layout.myLayoutName, container, false);
        btnAdd              = (Button) fragmentHandle.findViewById(R.id.btnAdd);


        btnAdd.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                // Get references from the views
                 mFirstNumber   = (EditText) view.findViewById(R.id.inputParam_A);
                 mSecondNumber  = (EditText) view.findViewById(R.id.inputParam_B);
                 m_resultHolder = (TextView) view.findViewById(R.id.textView_lblResult);

                // Get the actual usable values of views
                num1 = Double.parseDouble(mFirstNumber.getText().toString());
                num2 = Double.parseDouble(mSecondNumber.getText().toString());

                // Calculation Area
                result = num1 + num2;

                // Show Result
                m_resultHolder.setText(Double.toString(result));
            }
        });

        return fragmentHandle;
    }

    @Override
    public void onClick(View v) {

    }
}

 

Solution

In my case, the problem was in the line 25, 26, 27.  instead of “view.“, I need to dynamically get the current activity using “getActivity().“. As a result, the current activity reference is obtained dynamically and the error is resolved.

Here is the correct code. Please note the difference in lines 26, 26 and 27.

/**
 * Created by Codeonion on 9/26/2015.
 */
public class CustomFragmentClass extends Fragment implements View.OnClickListener{
    TextView mFirstNumber;
    EditText mSecondNumber;
    TextView m_resultHolder;
    Button btnAdd;
    double num1, num2, result;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View fragmentHandle = inflater.inflate(R.layout.myLayoutName, container, false);
        btnAdd              = (Button) fragmentHandle.findViewById(R.id.btnAdd);


        btnAdd.setOnClickListener(new OnClickListener()
        {
            @Override
            public void onClick(View view)
            {
                // Get references from the views
                 mFirstNumber   = (EditText) getActivity().findViewById(R.id.inputParam_A);
                 mSecondNumber  = (EditText) getActivity().findViewById(R.id.inputParam_B);
                 m_resultHolder = (TextView) getActivity().findViewById(R.id.textView_lblResult);

                // Get the actual usable values of views
                num1 = Double.parseDouble(mFirstNumber.getText().toString());
                num2 = Double.parseDouble(mSecondNumber.getText().toString());

                // Calculation Area
                result = num1 + num2;

                // Show Result
                m_resultHolder.setText(Double.toString(result));
            }
        });

        return fragmentHandle;
    }

    @Override
    public void onClick(View v) {

    }
}

Now, I will show you my app working.

Result

Now, when I input the values and press the button, the activities are obtained dynamically and the error does not appear any more.

As you see! swift arithmetic operation! Speaking of which, do check out my Android Tutorials Series for more!

Android Development Tutorials by Codeonion Learn more!

 

 


4 responses to “Android: How to fix “null object reference” error (with code)”

  1. What’d your code look like if your had to export your result to another Activity, and display it there ?

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: