petehallw petehallw - 10 months ago 44
Android Question

NullPointerException in Android application

I have a method which is returning a

object as a result of catching an exception. However, when I attempt to check this object I receive the following error:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method
'android.content.res.Resources android.content.Context.getResources()' on a
null object reference

My function is as follows:

public static DataPoint getDataFromArray() {
try {
return dataPoints[xIndex][yIndex];
catch (ArrayIndexOutOfBoundsException e) {
DataPoint dp = null;
return dp;

The value being returned is being checked in the following code:

DataPoint dp = getDataFromArray();

if(dp == null) {
Toast.makeText(AppContext.getAppContext(), "Out of bounds.", Toast.LENGTH_SHORT).show();

If I am unable to assign
to my
object then how should I go about this check? Thanks!

After resolving the application context, I am seeing the error:

java.lang.RuntimeException: Unable to start activity
java.lang.NullPointerException: Attempt to read from field
'short com.myandroid.myapp.Constants$DataPoint.status' on a null object reference

field is being read after the code I provided so I am not sure why it hasn't destroyed that activity first using the

Answer Source

The Context of your application is null.

Because when you call: AppContext.getAppContext(), the context is not yet set.

You should take a look at this answer:

public class MyApp extends Application {
 private static Context mContext;

    public static MyApp getInstance() {
        return instance;

    public static Context getContext() {
      //  return instance.getApplicationContext();
      return mContext;

    public void onCreate() {
    //  instance = this;
     mContext = getApplicationContext();