1

I am pretty new to java and android studio. I am trying to launch a new activity when the user is within a certain distance of a specified point on a map.

The following class determines the users distance from each point, when the user is within a certain distance (10m) I want a new activity to be launched where the user will be able to answer a question based on the location.

However when I try and start the new activity I get an error:

E/AndroidRuntime: FATAL EXCEPTION: main

Process: uk.ac.ucl.cege.cegeg077.ucfapwh.firstapp, PID: 6616
    java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
    at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:106)
    at uk.ac.ucl.cege.cegeg077.ucfapwh.firstapp.CustomLocationListener.onLocationChanged(CustomLocationListener.java:67)
    at android.location.LocationManager$ListenerTransport._handleMessage(LocationManager.java:281)
    at android.location.LocationManager$ListenerTransport.access$000(LocationManager.java:210)
    at android.location.LocationManager$ListenerTransport$1.handleMessage(LocationManager.java:226)
    at android.os.Handler.dispatchMessage(Handler.java:102)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5343)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)

Here is the code I have so far:

import android.app.Activity;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;

public class CustomLocationListener extends Map implements LocationListener {
public Map parentActivity ;
public ArrayList<GeoPoint> coordList;
// this method is called every time the user moves around - i.e. changes     location
// it pops up a toast message with the new coordinates
public void onLocationChanged(Location location) {

    // now measure distance from all the pre-set proximity alerts
    for (int i = 0; i < coordList.size(); i++) {

        // create GeoPoint object for each pair of coordinates
        GeoPoint gp = coordList.get(i);

        // create Location object
        Location fixedLoc = new Location("one");

        // get lat and lng values from GeoPoint object
        Float lat = Float.valueOf(String.valueOf(gp.getLatitude()));
        Float lng = Float.valueOf(String.valueOf(gp.getLongitude()));

        // set location for proximity alert
        fixedLoc.setLatitude(lat);
        fixedLoc.setLongitude(lng);

        // use Android distanceTo function to calculate the distances
        float distance = location.distanceTo(fixedLoc);

        Log.i("****DISTANCE****",String.valueOf(distance));
        Log.i("*****FIXEDLOC****", fixedLoc.toString());

        for (int j = 0; j < coordList.size(); j++ ) {

            if (i == j && distance < 120) {

                GeoPoint geoPoint = coordList.get(j);

                Log.i("****PROXI LAT*****", geoPoint.getLatitude().toString());
                Log.i("****PROXI LNG****", geoPoint.getLongitude().toString());

                Intent quizIntent = new Intent(getApplicationContext(),Questions.class);
                startActivity(quizIntent);

            }
        }

    }

}

// these methods are called when the GPS is switched on or off
// and will allow the App to warn the user and then
// shut down without an error
public void onProviderDisabled(String s) {
}
public void onProviderEnabled(String s) {
}

// this method is required by the LocationListener
// we do not need to do anything here
// but in a full implementation this could be used to react when the GPS signal is not available
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}

}

Apologies for the poor formatting. Any help would be greatly appreciated.

Kryten
  • 15,230
  • 6
  • 45
  • 68
pwhc
  • 516
  • 1
  • 6
  • 16

4 Answers4

2

Solved:

To retrieve the context from a non-activity class the following code is needed:

private Context context;

public NonActivityClass(Context context) {
    this.context = context.getApplicationContext();
}

Then to fire the Intent and start the new activity:

                Intent i = new Intent(context, Activity.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);

Thanks for the help.

get Context in non-Activity class

Community
  • 1
  • 1
pwhc
  • 516
  • 1
  • 6
  • 16
0

You can not use Application context to start the application. You should use activity context. If (guess)Map is your activity then update start activity code

Intent quizIntent = new Intent(this,Questions.class);
                startActivity(quizIntent);

For more details why application context can't be use to start activity https://possiblemobile.com/2013/06/context/

USKMobility
  • 5,721
  • 2
  • 27
  • 34
  • I get the following error by doing what you suggested: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName()' on a null object reference – pwhc Apr 25 '16 at 23:24
0

From my point of view you have two options to get it:

  1. Declare the CustomLocationListener as private inside the, let s say, NameOfYourActivity .

Next, change the Intent constructor from getApplicationContext() to NameOfYourActivity.this.

  1. Set the Context of the NameOfYourActivity as a property in CustomLocationListener, and then change the Intent constructor from getApplicationContext() to the context property.

Hope it helps

jos
  • 1,070
  • 12
  • 22
0

you are getting null because your class do not extends android activity. you can get application context in a non activity class like explained here.

Community
  • 1
  • 1
Zeeshan Bin Iqbal
  • 1,206
  • 2
  • 8
  • 8
  • I used the following code, im not sure if what im doing is correct: `public Context context; public CustomLocationListener(Context context) { this.context=context; }`. I then declared a new instance with the following: `Intent quizIntent = new Intent(new CustomLocationListener(this),Questions.class)`. However i got the same **java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String android.content.Context.getPackageName() on a null object** error – pwhc Apr 25 '16 at 23:26