0

I am creating an app that only checks for location when user clicks a button.

here is my code, and it returns null when i call getLastKnownLocation, even after I call requestLocationUpdates:

public void main(String[] args, int iteration, Context context){
    Criteria criteria = new Criteria();
    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);

    LocationListener loc_listener = new LocationListener() {
        public void onLocationChanged(Location l) {
        }
        public void onProviderEnabled(String p) {}
        public void onProviderDisabled(String p) {}
        public void onStatusChanged(String p, int status, Bundle extras) {}

        };

    String bestProvider = locationManager.getBestProvider(criteria, false);
    locationManager.requestLocationUpdates(bestProvider, 0, 0, loc_listener);
    Location location = locationManager.getLastKnownLocation(bestProvider);
    location = locationManager.getLastKnownLocation(bestProvider);
    double lat;
    double lon;
    try {
        lat = location.getLatitude();
        lon = location.getLongitude();

    } catch (NullPointerException e) {
        lat = -1.0;
        lon = -1.0;

    }
    Log.i("results:",  String.valueOf(lat) + " " + String.valueOf(lon) + " 10NN");}}

the location service on the device is enabled. Thanks very much!

Zhao Chen
  • 19
  • 1
  • 3
  • LastKnownLocation returns last known fix. So it is possible that it will be null. Try to look here http://stackoverflow.com/questions/7423624/how-reliable-is-locationmanagers-getlastknownlocation-and-how-often-is-it-updat – Alex Feb 19 '14 at 16:11
  • 1
    I tried to requestLocationUpdates and it doesn't actually update the last known location for me. – Zhao Chen Feb 19 '14 at 16:42
  • Did you find a solution – Questioner Jul 01 '16 at 10:30

2 Answers2

1

getLastKnownLocation will return null until the callback onLocationChanged() is triggered. This may take several minutes for GPS, even if the sky is clearly visible. If you are indoors it may never run. You have to wait for it to run.

NickT
  • 23,844
  • 11
  • 78
  • 121
  • my google map gets my location immediately. how did it do it? Also i tried to use requestLocationUpdates to get a update on location. but it didnt seem to work. – Zhao Chen Feb 19 '14 at 16:39
1

try this pls

  mGoogleMap.setOnMyLocationButtonClickListener(new OnMyLocationButtonClickListener() {

                    @Override
                    public boolean onMyLocationButtonClick()
                        {

                            Location myLocation = mGoogleMap.getMyLocation();
                            onLocationChanged(myLocation);
                            return false;
                        }
                });
Anil M H
  • 3,332
  • 5
  • 34
  • 51