-6

Okay so I am using this GPS location from GPS.class and I keep getting Null Object reference and not sure why.Here is my code:

 boolean permissionGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;

    if(permissionGranted)
    {
        if (GPS.sharedInstance(AppDashboard.this).canGetLocation() && GPS.sharedInstance(this).isPermissionEnabled()) {
            double lat = GPS.sharedInstance(AppDashboard.this).getLatitude();
            double lon = GPS.sharedInstance(AppDashboard.this).getLongitude();
            Log.e(TAG, "Location: " + lat + "/"+ lon);
        }
        else
        {
            Log.e(TAG, "Can't get GPS locations");
        }
    } else {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 200);
    }

My Manifest:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-feature android:name="android.hardware.location.gps" />

My Logcat:

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.gpsApp.utility.GPS.getLatitude(GPS.java:113)

And GPS Class 113

public double getLatitude() {
    if (_locationManager != null) {
        _latitude = _location.getLatitude();
    }

    return _latitude;
}
Jayce
  • 781
  • 3
  • 16
  • 35

2 Answers2

0

Use this line

boolean permissionGranted = ActivityCompat.checkSelfPermission(getApplicationContext, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;

Instead of this

 boolean permissionGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
Arslan Ali
  • 17
  • 6
0

You are calling public double getLatitude() from your GPS class, however the _location variable is not initialized hence you get the NullPointerException.

Prior calling getLatitude() try calling the public Location getLastKnownLocation() from your GPS class. This call will initialize the _location variable.

pleft
  • 7,567
  • 2
  • 21
  • 45