petehallw petehallw - 2 months ago 10
Android Question

NullPointerException in Android application

I have a method which is returning a

null
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();
finish();
}


If I am unable to assign
null
to my
DataPoint
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
ComponentInfo{com.myandroid.myapp/com.myandroid.myapp.activities.
DataEntryActivity}:
java.lang.NullPointerException: Attempt to read from field
'short com.myandroid.myapp.Constants$DataPoint.status' on a null object reference


This
status
field is being read after the code I provided so I am not sure why it hasn't destroyed that activity first using the
finish()
method.

Answer

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: http://stackoverflow.com/a/21994818/4585226

public class MyApp extends Application {
 private static Context mContext;

    public static MyApp getInstance() {
        return instance;
    }

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

    @Override
    public void onCreate() {
        super.onCreate();
    //  instance = this;
     mContext = getApplicationContext();    
    }