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

9

24

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();
}
Bionics answered 26/3, 2012 at 13:38 Comment(3)
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?Plasticity
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 locationBionics
you are using incorrect way follow this https://mcmap.net/q/224004/-getlastknownlocation-returns-nullTonkin
C
41

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.

Cyclostyle answered 26/3, 2012 at 13:48 Comment(3)
Why if (bestLocation == null) { return null; } return bestLocation; and not just return bestLocation; ? Also see hereDispose
NPE on log if location is nullEfrainefram
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?Gasbag
S
10

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"/>
Swatter answered 26/3, 2012 at 13:56 Comment(1)
This is beautifulFleshy
M
0

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) {}
}
Maletta answered 21/3, 2013 at 6:15 Comment(1)
Why are you using all the extra braces ??Dispose
H
0

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

Homozygote answered 4/12, 2016 at 6:35 Comment(0)
B
0

turn on your GPS by using below method. it helps you to show your current location without any ERROR. call it in onCreate

public void displayLocationSettingsRequest(Context context, int requestCode) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API).build();
    googleApiClient.connect();

    LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(10000 / 2);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);

    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(result1 -> {
        final Status status = result1.getStatus();
        if (status.getStatusCode() == LocationSettingsStatusCodes.RESOLUTION_REQUIRED)
            try {
                status.startResolutionForResult((Activity) context, requestCode);
            } catch (IntentSender.SendIntentException ignored) {
            }
    });
Bookstore answered 10/1, 2019 at 10:32 Comment(0)
D
0

If you are getting a null error with your provider list, change...

List<String> providers = mLocationManager.getProviders(true);

to...

List<String> providers = locationManager.getAllProviders();

This worked for me, and make sure that you have the following in your AndroidManifest.xml file...

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
Disyllable answered 1/4, 2019 at 0:59 Comment(0)
F
0

I think that this is a good optimized solution:

private lateinit var fusedLocationClient: FusedLocationProviderClient

override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)
...

fun clickMyLocation() {
    try {
        var locationManager = applicationContext.getSystemService(LOCATION_SERVICE) as LocationManager

        if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            fusedLocationClient.lastLocation
                .addOnSuccessListener { location : Location? ->
                    if (location == null) {
                        fusedLocationClient.getCurrentLocation(
                            LocationRequest.PRIORITY_HIGH_ACCURACY,
                            object : CancellationToken() {
                                override fun onCanceledRequested(p0: OnTokenCanceledListener) =
                                    CancellationTokenSource().token
                                override fun isCancellationRequested() = false
                            })
                            .addOnSuccessListener { location: Location? ->
                                if (location == null)
                                    showToast(getString(R.string.location_not_enabled))
                                else {
                                    setInTheCurrentPosition(location)
                                }
                            }
                    } else {
                        setInTheCurrentPosition(location)
                    }
                }
        } else {
            showToast(getString(R.string.collection_point_gps_desactivated))
        }
    }catch (e: Exception){
        showToast(getString(R.string.location_not_enabled))
    }
}

private fun setInTheCurrentPosition(location: Location?) {
    val pos = LatLng(location!!.latitude, location!!.longitude)
    gMap!!.animateCamera(
        CameraUpdateFactory.newLatLngZoom(
            pos,
            15f
        )
    )
    gMap!!.addMarker(MarkerOptions().position(pos))
}
Freddiefreddy answered 28/3, 2023 at 10:23 Comment(0)
F
0

My solution was to ensure that I requested for location forcefully. Add the following function in your class and call it just before onCreate method.

//imports
import com.google.android.gms.location.LocationCallback;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationResult;

the function

@SuppressLint("MissingPermission")
private void forceRequestLocation() {
    LocationRequest locationRequest = new LocationRequest.Builder(PRIORITY_HIGH_ACCURACY,100)
            .setWaitForAccurateLocation(false)
            .setMinUpdateIntervalMillis(2000)
            .setMaxUpdateDelayMillis(100)
            .build();

    LocationCallback locationCallback = new LocationCallback() {
        @Override
        public void onLocationResult(@NonNull LocationResult locationResult) {
            if (locationResult == null){
                return;
            }
        }
    };

    LocationServices.getFusedLocationProviderClient(getApplicationContext())
            .requestLocationUpdates(locationRequest,locationCallback,null);
}

This call ensures that you will never get a null location value. I found the solution at https://www.youtube.com/watch?v=KIZFPdvX6dM

I hope this helps someone.

Flute answered 14/9, 2023 at 12:37 Comment(0)
I
-2

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.

Inveigle answered 26/3, 2012 at 13:43 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.