My current location always returns null. How can I fix this?

52,151

Solution 1

getLastKnownLocation() uses the location(s) previously found by other applications. if no application has done this, then getLastKnownLocation() will return null.

One thing you can do to your code to have a better chance at getting as last known location- iterate over all of the enabled providers, not just the best provider. For example,

private Location getLastKnownLocation() {
    List<String> providers = mLocationManager.getProviders(true);
    Location bestLocation = null;
    for (String provider : providers) {
        Location l = mLocationManager.getLastKnownLocation(provider);
        ALog.d("last known location, provider: %s, location: %s", provider,
                l);

        if (l == null) {
            continue;
        }
        if (bestLocation == null
                || l.getAccuracy() < bestLocation.getAccuracy()) {
            ALog.d("found best last known location: %s", l);
            bestLocation = l;
        }
    }
    if (bestLocation == null) {
        return null;
    }
    return bestLocation;
}

If your app can't deal without having a location, and if there's no last known location, you will need to listen for location updates. You can take a look at this class for an example,

https://github.com/farble1670/autobright/blob/master/src/org/jtb/autobright/EventService.java

See the method onStartCommand(), where it checks if the network provider is enabled. If not, it uses last known location. If it is enabled, it registers to receive location updates.

Solution 2

if u find current location of devices the use following method in main class

public void find_Location(Context con) {
    Log.d("Find Location", "in find_location");
    this.con = con;
    String location_context = Context.LOCATION_SERVICE;
    locationManager = (LocationManager) con.getSystemService(location_context);
    List<String> providers = locationManager.getProviders(true);
    for (String provider : providers) {
        locationManager.requestLocationUpdates(provider, 1000, 0,
            new LocationListener() {

                public void onLocationChanged(Location location) {}

                public void onProviderDisabled(String provider) {}

                public void onProviderEnabled(String provider) {}

                public void onStatusChanged(String provider, int status,
                        Bundle extras) {}
            });
        Location location = locationManager.getLastKnownLocation(provider);
        if (location != null) {
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            addr = ConvertPointToLocation(latitude, longitude);
            String temp_c = SendToUrl(addr);
        }
    }
}

And Add User Permission method in your manifest file

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
Share:
52,151

Related videos on Youtube

devinefergal
Author by

devinefergal

Student Creating Android Application for Final project

Updated on November 16, 2021

Comments

  • devinefergal
    devinefergal over 2 years

    I am trying to find my current location for an android project. When the application is loaded my current location is always null. I have set up the permissions in the manifest etc. When I find the current location I intend to use the coordinates to find distances to other locations on the map. My code snippet is below. Why do I always get a null value?

    locMan = (LocationManager) getSystemService(Context.LOCATION_SERVICE);          
    Criteria crit = new Criteria();     
    towers = locMan.getBestProvider(crit, false);
    location = locMan.getLastKnownLocation(towers);    
    
    if (location != null) {                 
        System.out.println("Location is not null!");
        lat = (int) (location.getLatitude() *1E6);
        longi = (int) (location.getLongitude() * 1E6);
        GeoPoint ourLocation = new GeoPoint(lati, longi);
        OverlayItem overlayItem = new OverlayItem(ourLocation, "1st String",
                                                                "2nd String");
        CustomPinpoint custom = new CustomPinpoint(d, MainMap.this);
        custom.insertPinpoint(overlayItem);
        overlayList.add(custom);
        overlayList.clear();
    } else {
       System.out.println("Location is null! " + towers);
       Toast.makeText(MainMap.this, "Couldn't get provider",Toast.LENGTH_SHORT)
                                                                        .show();
    }
    
    • Boris Strandjev
      Boris Strandjev about 12 years
      Try accessing google maps directly not from the app. Does it work - locate you? after it locates you does your code run as expected? Do you test on device or emulator?
    • devinefergal
      devinefergal about 12 years
      I am testing on the emulator, I am using API level 15. It will not locate me, always returns null. I also tried accessing google maps application on the emulator, it also cannot find location
    • Binesh Kumar
      Binesh Kumar over 6 years
      you are using incorrect way follow this stackoverflow.com/a/48033659/4997704
  • Mr_and_Mrs_D
    Mr_and_Mrs_D almost 11 years
    Why are you using all the extra braces ??
  • Mr_and_Mrs_D
    Mr_and_Mrs_D almost 11 years
    Why if (bestLocation == null) { return null; } return bestLocation; and not just return bestLocation; ? Also see here
  • Ravindranath Akila
    Ravindranath Akila over 10 years
    NPE on log if location is null
  • Utsav Gupta
    Utsav Gupta over 8 years
    I am getting lastknownloc as null in my app, but other apps like google maps are working on the same device. Can anyone suggest how is this happenng?
  • stepheaw
    stepheaw almost 7 years
    This is beautiful