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

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();
}

  • Can't connect Nexus 4 to adb: unauthorized
  • HTML5 <video> element on Android
  • Android TextView with multiple lines
  • Generating and installing SSL certificates
  • is it ok to create ORMLite database helper in Application class?
  • Can someone provide a good explanation of Dagger 2?
  • Android Studio - no debuggable applications
  • Using layout_above in a RelativeLayout
  • Android Speech Recognition API does not work in Android 7 Nougat
  • Developing an Android Homescreen
  • Change DatePickerDialog's button texts
  • adb command not found
  • 5 Solutions collect form web for “My current location always returns null. How can I fix this?”

    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.

    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"/>
    

    Have you tried reversing the code? For example, if(location==null) then print that location is null, and else print location is not null. I got that problem once before and that seemed to have fixed it (i don’t know why). Try that.

    If that doesn’t work, perhaps the google maps API is returning the null value, in which case its a problem with the GM-API or with the call method. Any of these could be the problem.

    Hope this helps,

    -JXP

    Try this this will not give you null current location

    class GetLastLocation extends TimerTask {
    
        LocationManager mlocManager = (LocationManager) 
                getSystemService(Context.LOCATION_SERVICE);
        LocationListener mlocListenerTmp = new CustomLocationListener();
        private final Handler mLocHandler;
    
        public GetLastLocation(Handler mLocHandler) {
            this.mLocHandler = mLocHandler;
        }
    
        @Override
        public void run() {
            timer.cancel();
            mlocManager.removeUpdates(mlocListenerTmp);
            Location location = mlocManager
                    .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
            {
                if (mlocListenerTmp != null) {
                    mlocManager.removeUpdates(mlocListenerTmp);
                }
                currentLocation = location;
            }
            if (location != null) {
                String message = String.format(
                    "Location \n Longitude: %1$s \n Latitude: %2$s",
                    location.getLongitude(), location.getLatitude());
                Log.d("loc", " :" + message);
                Bundle b = new Bundle();
                {
                    b.putBoolean("locationRetrieved", true);
                    {
                        Message msg = Message.obtain();
                        {
                            msg.setData(b);
                            mLocHandler.sendMessage(msg);
                        }
                    }
                }
            } else {
                Log.d(
                    "loc",
                    ":No GPS or network signal please fill the location manually!");
                location = mlocManager
                        .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                if (location != null) {
                    currentLocation = location;
                    Bundle b = new Bundle();
                    {
                        b.putBoolean("locationRetrieved", true);
                        {
                            Message msg = Message.obtain();
                            {
                                msg.setData(b);
                                mLocHandler.sendMessage(msg);
                            }
                        }
                    }
                } else {
                    Bundle b = new Bundle();
                    {
                        b.putBoolean("locationRetrieved", false);
                        {
                            Message msg = Message.obtain();
                            {
                                msg.setData(b);
                                mLocHandler.sendMessage(msg);
                            }
                        }
                    }
                }
            }
        }
    }
    

    call it like this

    timer.schedule(new GetLastLocation(mLocHandler), 3000);
    

    and the customLocationclass is as follows

    public class CustomLocationListener implements LocationListener {
    
        @Override
        public void onLocationChanged(Location loc) {
            loc.getLatitude();
            loc.getLongitude();
            currentLocation = loc;
            String Text = "My current location is: " + "Latitud = "
                + loc.getLatitude() + "Longitud = " + loc.getLongitude();
            Log.d("loc", "onLocationChanged" + Text);
        }
    
        @Override
        public void onProviderDisabled(String provider) {}
    
        @Override
        public void onProviderEnabled(String provider) {}
    
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {}
    }
    

    If you are trying it out in a marshmallow device, try enabling location permission for your app manually.

    Android Babe is a Google Android Fan, All about Android Phones, Android Wear, Android Dev and Android Games Apps and so on.