-3

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.

petehallw
  • 1,014
  • 6
  • 21
  • 49

1 Answers1

0

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: https://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();    
    }
Community
  • 1
  • 1
476rick
  • 2,764
  • 4
  • 29
  • 49
  • Thanks, I see. However I am now getting this error `java.lang.NullPointerException: Attempt to read from field 'short com.myapp.$DataPoint.status' on a null object reference` relating to my null object, which I thought may have been causing an issue also... – petehallw Sep 21 '16 at 13:14
  • I do not see this error in your question, you should add it. – 476rick Sep 21 '16 at 13:17
  • Edited the post :-) – petehallw Sep 21 '16 at 13:22