2

I followed this tutorial http://developer.android.com/training/location/retrieve-current.html to retrieve the position of my device but it don't work.

When I do this :

mLastLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);

"mLastLocation" is null, why ?

Edit

I tried to do like in the answere of Niru :

public Location setLocation()
    {
        Location location;
        final int MIN_TIME_BW_UPDATES = 300;
        final int MIN_DISTANCE_CHANGE_FOR_UPDATES = 50;
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        criteria.setPowerRequirement(Criteria.POWER_LOW);

        locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

        String bestProvider = locationManager.getBestProvider(criteria, true);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        {
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {}
        }

        location = locationManager.getLastKnownLocation(bestProvider);

        localStorage.putFloat("latitude", (float) location.getLatitude());
        localStorage.putFloat("longitude", (float) location.getLongitude());
        localStorage.commit();

        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, MIN_TIME_BW_UPDATES, MIN_DISTANCE_CHANGE_FOR_UPDATES, (LocationListener) this);



        return location;
    }

    @Override
    public void onLocationChanged(Location location)
    {
        localStorage.putFloat("latitude", (float) location.getLatitude());
        localStorage.putFloat("longitude", (float) location.getLongitude());
        localStorage.commit();
    }

But "location" is Null, Why ?

JohnyBro
  • 341
  • 3
  • 14
  • 2
    Possible duplicate of [LocationClient getLastLocation() return null](http://stackoverflow.com/questions/16830047/locationclient-getlastlocation-return-null) – fweigl Dec 12 '15 at 18:22
  • Same problem here with a Nexus 6p on Android 6.0 and a Nexus 5 on Android 6.0.1 but It works well on a Nexus 4 on 5.1.1 so maybe it's a platform issue... Which version of Android do you use ? – Nicolas Mauti Dec 12 '15 at 18:33

3 Answers3

1

You can try the following code snippet:

public class LocationProvider
{
    private static final String     TAG         = "DEBUG";
    private static final String[]   provider    = new String[]
                                                {
            LocationManager.GPS_PROVIDER,
            LocationManager.NETWORK_PROVIDER,
            LocationManager.PASSIVE_PROVIDER
                                                };

    public Location getLocationByProvider(Context context)
    {
        Location location = null;
        // LocationManager locationManager = (LocationManager) context.getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        try
        {
            for (int i = 0; i < provider.length; i++)
            {
                if (locationManager.isProviderEnabled(provider[i]))
                {
                    // locationManager.requestLocationUpdates(provider[i], 0, 0, locationListenerGps);
                    location = locationManager.getLastKnownLocation(provider[i]);
                    if (location != null)
                    {
                        break;
                    }
                }
            }
        }
        catch (IllegalArgumentException e)
        {
            Log.d(TAG, "Cannot acces Provider " + provider);
        }
        return location;
    }

}

you can also get best provider and then get location from best provider.

mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
            Criteria criteria = new Criteria();
            criteria.setAccuracy(Criteria.ACCURACY_FINE);
            criteria.setAltitudeRequired(false);
            criteria.setBearingRequired(false);
            criteria.setCostAllowed(true);
            criteria.setPowerRequirement(Criteria.POWER_LOW);
            bestProvider = mLocationManager.getBestProvider(criteria, true);

Hope this will helps you. :-)

Niru
  • 489
  • 6
  • 15
0

The documentation itself says that getLastLocation may return null in cases when location is not available. When it is null, call requestLocationUpdate method in the OnConnected() method, like this :

@Override
public void onConnected(Bundle connectionHint) {
    mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    if (mCurrentLocation == null) {
        LocationServices.FusedLocationApi.requestLocationUpdates(
            mGoogleApiClient, mLocationRequest, this);
    }
}

Before calling the requestLocationUpdates, create the mLocationRequest object:

mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);   
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);

When the location will be available, OnLocationChanged will get fired automatically. The rate of getting this callback is defined by the interval you put in setInterval() while creating the request object.

@Override
public void onLocationChanged(Location location) {
    mCurrentLocation = location;        
}

Your location object will get updated then.

Follow this link: http://developer.android.com/training/location/receive-location-updates.html

proy31
  • 123
  • 12
0

I solve my similar issue thanks to this post : Permission issues for location in android Marshmallow applicaton.

In fact, if you use compileSdkVersion 23 (or higher) you have to handle the new android permission system if you want that your application run correctly on Android 6.0+ devices... More informations can be found here : http://developer.android.com/training/permissions/index.html.

One quick-and-dirty workaround for testing your app can be to change your compileSdkVersionand targetSdkVersion in your build.gradle to 22...

However, I think it's stupid that there is no clear error message about this but just a null...

Community
  • 1
  • 1
Nicolas Mauti
  • 506
  • 3
  • 13