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!

 

 

Codeonion contributes to the honorable mission of “helping people learn and earn online”. Whether your day job is creative or not, life is better when you learn and apply creative skills regularly. To do this is satisfying in its own right and a practical investment in your future.

Comments (4)

  1. Thank you so much for this! I’ve spent days looking for a solution and this has finally worked for me, thanks!

  2. Austin says:

    How tf do i get there my phone is constantly getting the message

  3. Austin says:

    How tf do i get there my phone is constantly getting the message

  4. Anonymous says:

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

Leave a Reply

Your email address will not be published.

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