17

I had just got this to work but when I turned off my Wifi to see if I could get a more accurate location using my GPS it's now bringing me a NullPointer error and I can't see why.

The below code gets called first;

 public void onConnected(Bundle dataBundle) {
        connected = true;
        //Request an update from the location client to get current Location details
        mLocationClient.requestLocationUpdates(mLocationRequest,this);
        Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
    }

Which then entails this method being called

public void onLocationChanged(android.location.Location location) {
        // Report to the UI that the location was updated
        String msg = "Updated Location: " +
                Double.toString(location.getLatitude()) + "," +
                Double.toString(location.getLongitude());
        if(tmp != location.getLatitude())
        {
            Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
        }
        tmp = location.getLatitude();
    }

You can see I have 2 toasts there and they come back fine with the actual GPS coordinates but when I call the below code it crashes out on the new location line getLastKnownLocation

public String getLocation()
    {
        // Get the location manager
        LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
        Criteria criteria = new Criteria();
        String bestProvider = locationManager.getBestProvider(criteria, false);
        android.location.Location location = locationManager.getLastKnownLocation(bestProvider);
        Double lat,lon;
        DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        Date date = new Date();
        try {
            lat = location.getLatitude ();
            lon = location.getLongitude ();
            Toast.makeText(this,""+lat.toString()+"-"+lon.toString(),Toast.LENGTH_SHORT).show();
            return new LatLng(lat, lon).toString();
        }
        catch (NullPointerException e){
            Toast.makeText(this,"HELL-NO",Toast.LENGTH_SHORT).show();
            Log.e("HELL-NO","n",e);
            e.printStackTrace();
            return null;
        }
    }

I just don't get why when I try to retrieve the location, which seems to have been retrieved in the onLocationChanged method, it just comes up with a nullpointer.

r0bb077
  • 732
  • 2
  • 11
  • 33

4 Answers4

34

I simply changed

locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER) to 
locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);

This solved the solution for me. Complete snippet:

map  = ((MapFragment) getFragmentManager().
            findFragmentById(R.id.map)).getMap();

    map.setMyLocationEnabled(true);

    locationManager = (LocationManager)getSystemService
            (Context.LOCATION_SERVICE); 
    getLastLocation = locationManager.getLastKnownLocation
            (LocationManager.PASSIVE_PROVIDER);
    currentLongitude = getLastLocation.getLongitude();
    currentLatitude = getLastLocation.getLatitude();

    currentLocation = new LatLng(currentLatitude, currentLongitude); 

Hope this helps.

duggu
  • 37,851
  • 12
  • 116
  • 113
Troy Zuroske
  • 762
  • 1
  • 12
  • 31
  • 3
    it works for me but whats the difference between GPS_PROVIDER and PASSIVE_PROVIDER ? – Aishwat Singh Mar 28 '16 at 12:44
  • @TroyZuroske Any idea why the passive provider fixes this problem? Sorry for the bump. Worked for me too, thanks! – Kevin Van Ryckegem Sep 14 '16 at 14:55
  • 2
    it doesnt work.... Location location = locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER); Log.d(TAG, "OnRes:lastknown:" + locationManager.getLastKnownLocation(LocationManager.PASSIVE_PROVIDER)); Log.d(TAG, "OnRes:lastknown:" + location); gives me null in the logcat – Aalap Patel Sep 16 '16 at 18:23
7

you are mixing the new and the old location API's together when you shouldnt.

to get the last known location all your have to do is call

mLocationClient.getLastLocation();

once the location service was connected.

read how to use the new location API

http://developer.android.com/training/location/retrieve-current.html#GetLocation

tyczj
  • 71,600
  • 54
  • 194
  • 296
2

try this code:

LocationManager mLocationManager;
Location myLocation = getLastKnownLocation();

private Location getLastKnownLocation() {
    mLocationManager = (LocationManager)getApplicationContext().getSystemService(LOCATION_SERVICE);
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        if (l == null) {
            continue;
        }
        if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
            // Found best last known location: %s", l);
            bestLocation = l;
        }
    }
    return bestLocation;
}
Khalid Taha
  • 3,183
  • 5
  • 27
  • 43
0

I struggled with this one for a long time. But Google just came up with a solution.

googleMap.getMyLocation();

to get the location of the blue dot on api V2.

The_Martian
  • 3,684
  • 5
  • 33
  • 61