0

I'm trying to obtain the user's location, and this seems to be giving me trouble. When I call distanceBetween() to see test if it's working I get a NullPointerException at getApplicationContext(). Is there something I am not doing?

Here is the Stacktrace:

java.lang.NullPointerException at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:109) at com.ayy.zz.DistanceFinder.onCreate(DistanceFinder.java:38) at com.ayy.zz.DistanceFinder.distanceBetween(DistanceFinder.java:82) at com.ayy.zz.DistanceFinderTests.testSomething(DistanceFinderTests.java:14) at java.lang.reflect.Method.invokeNative(Native Method) at student.TestCase.runBare(TestCase.java:108) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191) at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176) at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:554) at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1701)

TestSomething is simply initializing a DistanceFinder and calling the distanceBetween method:

    public double distanceBetween()
    {
        onCreate();
        return dining1.distanceTo(dining2);
    }

1 Answers1

2

You cannot simply call onCreate in order to get the context. It isn't clear what you are trying to do or when you are calling distanceBetween but it is obviously at a time before Android "creates" the Activity. (What is 'Context' on Android?)

Also, your mContext should not be static, and although it is permissible, this will give you access to the variable even when an instance is not created, also giving you an NPE.

When you are accessing Context you will need to be sure that Android has actually created / passed in a context for your object. In this case, an Activity must be "launched" before it will have context. This is true of Service and BroadcastReceiver classes as well.

Here are four solutions to getting Context -

  1. Pass it into the method call, like this:
public double distanceBetween(Context mContext)
{
    locationManager = (LocationManager) mContext
        .getSystemService(Context.LOCATION_SERVICE);
    dining1 = new Location("");
    dining1.setLatitude(37.226500);
    dining1.setLongitude(-80.419179);
    dining2 = new Location("");
    dining2.setLatitude(37.229219);
    dining2.setLongitude(-80.418310);
    return dining1.distanceTo(dining2);
}
  1. Only call your method after the Activity is created by Android (not jsut by calling onCreate()

  2. Create a Service and pass your requests to the Service and use its Context

http://www.vogella.com/tutorials/AndroidServices/article.html

  1. Cautiously consider using the Application class, which should be accessible any time your app is running.
Community
  • 1
  • 1
Jim
  • 10,172
  • 1
  • 27
  • 36