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

As evident from my Logcat as well.

 

Problematic code is given below:

 

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.

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!

 

 

Liked it? Take a second to support codeonion on Patreon!

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

Leave a Reply

Your email address will not be published.