25

Recently, I created a simple application to get the gps location and display on android phone. At beginning I able to get the location after few try, but after i re-install the apk file, the getLastKnownLocation() always return a null value.

Development environment used: - API 10 gingerbread 2.3.6 - GPS provider is used

below is the code i applied in my android project:

        public class MyActivity extends MapActivity{
protected void onCreate(Bundle savedInstanceState) {


    mapView = (MapView)findViewById(R.id.myTripMap);
    mapController = mapView.getController();
    mapView.setSatellite(false);
    mapView.setStreetView(true);
    mapView.displayZoomControls(false);
    mapView.setBuiltInZoomControls(true);//
    mapView.setClickable(true);
    mapController.setZoom(14);      


    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setAltitudeRequired(false);
    criteria.setBearingRequired(false);
    criteria.setCostAllowed(true);
    criteria.setPowerRequirement(Criteria.POWER_LOW);
    provider = locationManager.getBestProvider(criteria, true);
    location = locationManager.getLastKnownLocation(provider);

    updateMyCurrentLoc(location);

    locationManager.requestLocationUpdates(provider, 2, 1,locationListener);



}


          private final LocationListener locationListener = new LocationListener() {
        public void onLocationChanged(Location location) {
          updateMyCurrentLoc(location);
        }

        public void onProviderDisabled(String provider){
          updateMyCurrentLoc(null);
        }

        public void onProviderEnabled(String provider){ }
        public void onStatusChanged(String provider, int status, 
                                    Bundle extras){ }
      };


      private void updateMyCurrentLoc(Location location) {



            if (location != null) {

             // other codes to get the address and display
            Toast.makeText(getBaseContext(), "provider used : "+provider).show();   //testing purpose
            } 
            else {
              str = "No location found";
              Toast.makeText(getBaseContext(), str, Toast.LENGTH_SHORT).show();
            }

        }
    }

Can anyone suggest a possible solution to solve the null value returned by getLastKnownLocation()? Any helps will be appreciated. Thanks.

Student
  • 521
  • 1
  • 9
  • 16

5 Answers5

44

the getLastKnownLocation() this returns the last known location...after you re-install the app it will not have any last known location...so it will result in NPE...instead use below code

public Location getLocation() {
    try {
        locationManager = (LocationManager) mContext
                .getSystemService(LOCATION_SERVICE);

        // getting GPS status
        isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (!isGPSEnabled && !isNetworkEnabled) {
            // no network provider is enabled
        } else {
            this.canGetLocation = true;
            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                    if (location != null) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                    }
                }
            }
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
            }
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

    return location;
}

It worked for me...should work for you too...

karan
  • 8,812
  • 3
  • 41
  • 76
  • 19
    It's not that great code.. putting all code inside a try/catch without any of it explicitly needing it it is bad programming in principle. If you really want a great piece of code, try this: https://web.archive.org/web/20100429083435/http://marakana.com/forums/android/android_examples/42.html – Henrique de Sousa Dec 09 '13 at 10:26
  • @Karan Mer i get a different Longitude and Latitude on different cell phones using the same Network (Vodafone) at the same place. What do i do in this case – Sagar Devanga Dec 27 '14 at 08:32
  • 9
    This is wrong on so many levels I don't know how to say it. First off, getLastKnownLocation returns the devices last known location, not the apps. It will return null if the device isn't already tracking the location. So your code can still return null, and will do so regularly. There's a dozen other mistakes in that code as a bonus. – Gabe Sechan May 26 '15 at 08:23
  • 5
    Even GPS is enabled unable to get location from GPS_PROVIDER in my case. every time getting from NETWORK_PROVIDER. Any idea ?? CAn any one help me out. – B Bhanu Chander Oct 08 '15 at 14:35
  • From where do I get locationListener? – Narendra Singh Apr 11 '16 at 12:37
  • 4
    getLastKnownLocation still returns null! Didnt work for me – Anil P Babu Aug 11 '16 at 13:59
  • @anil_pulikoden: answer is much old, with the new updates needed to update the answer but didn't had much time to test this. will do this sometimes sooner. – karan Aug 11 '16 at 14:01
  • it doesn't work for me. I'm doing same thing in xamarin – Kishan Kumar Aug 12 '16 at 01:33
1

This solution is my little improvement for @Karan Mer code.

    public Location getLocation() {
    int MIN_TIME_BW_UPDATES = 10000;
    int MIN_DISTANCE_CHANGE_FOR_UPDATES = 10000;
    try {
        locationManager = (LocationManager) getApplicationContext()
                .getSystemService(LOCATION_SERVICE);

        boolean isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        boolean isPassiveEnabled = locationManager
                .isProviderEnabled(LocationManager.PASSIVE_PROVIDER);

        boolean isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

        if (isGPSEnabled || isNetworkEnabled || isPassiveEnabled) {

            this.canGetLocation = true;
            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled && location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("GPS", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                    }
            }
            if (isPassiveEnabled && location == null) {
                locationManager.requestLocationUpdates(
                        LocationManager.PASSIVE_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.PASSIVE_PROVIDER);
                }
            }

            if (isNetworkEnabled && location == null) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                Log.d("Network", "Network Enabled");
                if (locationManager != null) {
                    location = locationManager
                            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                }
            }

        }else{
            return null;
        }

    } catch (Exception e) {
        e.printStackTrace();
    }

Enjoy

Oded BD
  • 2,148
  • 21
  • 26
0

You just need to add one more line into the code

if (locationManager != null) {
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    location = locationManager
            .getLastKnownLocation(LocationManager.GPS_PROVIDER);

    if (location != null) {
        latitude = location.getLatitude();
        longitude = location.getLongitude();

    } else {
        Toast.makeText(
                mContext,
                "Location Null", Toast.LENGTH_SHORT).show();
    }
}
Mauker
  • 11,011
  • 7
  • 54
  • 73
  • what if location==null ? How to get exact location – Anand Savjani Jan 24 '17 at 11:17
  • 1
    wait whats wrong with you, I dont know what exactly are you trying to answer. The question is here for someone to tell him solution, how to get rid of this null object being returned on getLastKnownLocation(PROVIDER)method. Not to show a toast message, without any suggestion what to do next. – Khay Mar 20 '17 at 18:33
0

Try Following Code

LocationManager locationManager = (LocationManager) getActivity()
            .getSystemService(Context.LOCATION_SERVICE);

    String locationProvider = LocationManager.NETWORK_PROVIDER;
    Location lastlocation = locationManager.getLastKnownLocation(locationProvider);

    String CurLat = String.valueOf(lastlocation.getLatitude());
    String Curlongi= String.valueOf(lastlocation.getLongitude());
Dhanveer thakur
  • 802
  • 1
  • 9
  • 16
-2

I got the same issue after re-install via eclipse. I solved going to Android settings / Security / app permissions and confirm location permissions to the application.

  • 2
    That is not the way you need to ask user to grant those permissions in runtime. [for more info check this](https://developer.android.com/guide/topics/security/permissions.html#normal-dangerous) – Kaushik Oct 13 '16 at 10:47