66

Like the questions someone encountered before I tested one the nexus s(4.0.4 with google play service available) and avd (4.2.2 with google api), in both case locationclient's getLastLocation() always return null.

public class MainActivity extends Activity implements LocationListener,
        GooglePlayServicesClient.ConnectionCallbacks,
        GooglePlayServicesClient.OnConnectionFailedListener {

    private LocationClient mLocationClient;
    private LocationRequest mLocationRequest;
    boolean mUpdatesRequested = false;
    boolean mConnected = false;
    SharedPreferences mPrefs;
    SharedPreferences.Editor mEditor;
    private TextView mText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mText = (TextView) findViewById(R.id.text);
        mLocationRequest = LocationRequest.create();
        mLocationRequest
                .setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationRequest
.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
        mUpdatesRequested = false;
        mPrefs = getSharedPreferences(LocationUtils.SHARED_PREFERENCES,
                Context.MODE_PRIVATE);
        mEditor = mPrefs.edit();
        mLocationClient = new LocationClient(this, this, this);
    }
    @Override
    public void onStart() {
        super.onStart();
        /*
         * Connect the client. Don't re-start any requests here; instead, wait
         * for onResume()
         */
        mLocationClient.connect();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // If the app already has a setting for getting location updates, get it
        if (mPrefs.contains(LocationUtils.KEY_UPDATES_REQUESTED)) {
            mUpdatesRequested = mPrefs.getBoolean(
                    LocationUtils.KEY_UPDATES_REQUESTED, false);
            // Otherwise, turn off location updates until requested
        } else {
            mEditor.putBoolean(LocationUtils.KEY_UPDATES_REQUESTED, false);
            mEditor.commit();
        }
    }
    @Override
    public void onStop() {
        // If the client is connected
        if (mLocationClient.isConnected()) {
            stopPeriodicUpdates();
        }
        // After disconnect() is called, the client is considered "dead".
        mLocationClient.disconnect();
        super.onStop();
    }

    @Override
    public void onPause() {
        // Save the current setting for updates
        mEditor.putBoolean(LocationUtils.KEY_UPDATES_REQUESTED,
                mUpdatesRequested);
        mEditor.commit();
        super.onPause();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
    public void getLocation(View v) {
        // If Google Play Services is available
        if (isGooglePlayServicesAvailable()) {
            if (!mConnected)
                mText.setText("location client is not connected to service yet");
            else {
                // Get the current location
                Location currentLocation = mLocationClient.getLastLocation();
                // Display the current location in the UI
                mText.setText(LocationUtils.getLocationString(currentLocation));
            }
        }
    }

    private boolean isGooglePlayServicesAvailable() {

        // Check that Google Play services is available
        int resultCode = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(this);

        // If Google Play services is available
        if (ConnectionResult.SUCCESS == resultCode) {
            // In debug mode, log the status
            Log.d(LocationUtils.APPTAG, "google play service is available");

            // Continue
            return true;
            // Google Play services was not available for some reason
        } else {
            // Display an error dialog
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode,
                    this, 0);
            if (dialog != null) {
                Log.e(LocationUtils.APPTAG,
                        "google play service is unavailable");
            }
            return false;
        }
    }

    private void stopPeriodicUpdates() {
        mLocationClient.removeLocationUpdates(this);
        // mConnectionState.setText(R.string.location_updates_stopped);
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        mConnected = false;
        Log.d(LocationUtils.APPTAG, "connection failed");
    }

    @Override
    public void onConnected(Bundle arg0) {
        mConnected = true;
        Log.d(LocationUtils.APPTAG,
                "location client connected to the location server");
        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        lm.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0,
                new android.location.LocationListener() {
                    @Override
                    public void onStatusChanged(String provider, int status,
                            Bundle extras) {}

                    @Override
                    public void onProviderEnabled(String provider) {}

                    @Override
                    public void onProviderDisabled(String provider) {}

                    @Override
                    public void onLocationChanged(final Location location) {
                    }
                });
        Log.d(LocationUtils.APPTAG, "done trying to get location");
    }

    @Override
    public void onDisconnected() {
        // TODO Auto-generated method stub
        mConnected = false;
        Log.d(LocationUtils.APPTAG,
                "location client disconnected from the location server");
    }

    @Override
    public void onLocationChanged(Location arg0) {}

}

most of them came from examples given by google. In the code above hava tried the method like that:

LocationRequest request = LocationRequest.create();
request.setNumUpdates(1);
mLocationClient.requestLocationUpdates(request, this);

and

LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        lm.requestLocationUpdates(LocationManager.PASSIVE_PROVIDER, 0, 0,
                new android.location.LocationListener() {
                    @Override
                    public void onStatusChanged(String provider, int status,Bundle extras) {}

                    @Override
                    public void onProviderEnabled(String provider) {}

                    @Override
                    public void onProviderDisabled(String provider) {}

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

In onConnected() before calling getLastLocation(), but still get no luck. Where's the mistake?

4
  • you should accept an answer or suggest how you solved your problem. Commented Dec 5, 2013 at 21:46
  • @twntee currently i just using <lac,ci> for instance location, but for the answers i chose the first one~ Commented Dec 6, 2013 at 2:08
  • grt... it encourages people to answer more and also helps future visitors :) Commented Dec 6, 2013 at 10:13
  • I had the same case, only a restart of the phone corrected the behaviour. I received a permanent NULL object and network location failed in general. After a cold reset it worked again as it should and getLastLocation() returned an object.
    – John
    Commented Feb 17, 2014 at 2:42

13 Answers 13

56

Currently the Fused Location Provider will only maintain background location if at least one client is connected to it. Once the first client connects, it will immediately try to get a location. If your activity is the first client to connect and you call getLastLocation() right away in onConnected(), that might not be enough time for the first location to come in.

4
  • 5
    ok..i agree..but should i continously call getLastLocation() in thread until it returns a not null value..
    – Anirudha
    Commented Aug 18, 2013 at 16:02
  • 41
    getLastLocation is good for "best effort" cases where a location is needed immediately or none at all can be used. If you really want to wait for a location it's best to use requestLocationUpdates and wait for the callback rather than busywaiting in a thread. If you just want one location, you can specify that in the LocationRequest, and the request will automatically be removed once your update comes in.
    – David
    Commented Sep 18, 2013 at 6:11
  • 4
    Hey David, may i ask how you know the thing about "at least one client"?... would be an intersting read.
    – Mathias
    Commented Feb 2, 2014 at 22:58
  • If a location is not available, which should happen very rarely, null will be returned. Check the documentation, developer.android.com/reference/com/google/android/gms/location/… Commented Feb 27, 2015 at 17:36
22

I had the same problem when following the instructions from the tutorial. On phone it worked and on the (Genymotion) emulator it didn't.

Solution

In your AndroidManifest.xml, change this:

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

to this:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

...and you get the location immediately. No need to change your code (to listen to location updates).

7
  • 8
    In GenyMotion with GApps added, you also have to enable Location Access setting and run google map at least once (if you don't have google map, you have to install it first from play store).
    – null
    Commented Aug 31, 2014 at 8:59
  • 2
    This is a workaround not a solution. What if we don't want to force fine location permission requirement onto the user?
    – Nilzor
    Commented Sep 29, 2014 at 10:45
  • 2
    @Nilzor - this is probably no use to you any more, given the time that's passed, but (if you're working with Android Studio, at least) you can create an AndroidManifest.xml under src/debug which will get merged into the main manifest for debug builds but will not get merged for release builds. Maybe this will help someone else with the same problem in the future...
    – Zac Seth
    Commented May 13, 2015 at 15:02
  • 1
    It doesn't help to me
    – Androider
    Commented Jan 27, 2016 at 13:28
  • i use the same permission but still null value i get. Commented Oct 5, 2016 at 18:00
20

The issue can also be caused by your device does not have "Wi-Fi & mobile network location" enabled.

LocationClient (the fused location provider) uses both GPS and WiFi. GPS takes a while to find your location while wifi is much faster. However, if any one of these 2 services is connected, the call back method onConnected will be called. And if you are trying to call LocationClient.getLastLocation() in the onConnected method immediately, it is mostly likely that you will get null value if your wifi location service is disabled. It is just because GPS is simply not fast enough.

To solve the problem for yourself locally, enable "Wi-Fi & mobile network location". You can do it by going to "Settings > Personal > Location access > Wi-Fi & mobile network location".

However, if you want to solve the issue for the users of your app, you'd better check whether getLastLocation() returns null. If it does, prompt your user to enable the service just like google map does.

Hopefully, that helps.

4
  • 2
    I just had the case that getLastLocation() returned null if GPS is disabled. Even if location settings enable everything it returns NULL at any time and I never receive a location update at all. If I enable GPS it works again. Fresh restarting the app did not solve the problem. Restarting the Phone however made periodic updates possible again, even without GPS. At this point I think it might be possible that the Play Service fused location API is not as reliable as the integrated one.
    – John
    Commented Feb 17, 2014 at 2:40
  • Hm... I am not if I read your comment correctly. So I may misunderstand you. If you read my answer more carefully, you will realize you don't need GPS enabled. It is more about your "Wifi & mobile network location" enabled. It is faster than GPS and should be more reliable in urban area. Let me know if I am wrong. =)
    – Tim Hong
    Commented Feb 17, 2014 at 9:15
  • 2
    I am aware of that. I just tried to add that I encountered such a problem regardless of Wifi & mobile network location enabled. The Google Play location services somehow got stuck internally and only a reboot of the phone itself brought it back to normal. So far it happened only once to me.
    – John
    Commented Feb 18, 2014 at 19:41
  • 1
    @john this has happened to me on multiple occations in development and I suspect also production. Still looking for solutions, so shout out if you find any.
    – Nilzor
    Commented Sep 29, 2014 at 10:47
7

I was facing a similar issue.

Call mLocationClient.getLastLocation() in onConnected or after the Connection to Google Play Services has been established. If you're calling this method before the Location Client is connected, the location returned would be null.

You could check if the location client is connected by mLocationClient.isConnected().

Hope this helps.

6

I faced similar issues on my tests with Samsung phones (highly customized android, and no developer support).

LocationManager and LocationClient dont get the GPS from the providers. They need to be kickstarted everytime you need the location from them. Do this before your LocationManager.getLastKnownLocation OR LocationClient.getLastLocation calls. These API's will return.

YOUR_APPLICATION_CONTEXT.getLocationManager().requestLocationUpdates(
    LocationManager.NETWORK_PROVIDER, 0, 0, new LocationListener() {
        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
        }
        @Override
        public void onProviderEnabled(String provider) {
        }
        @Override
        public void onProviderDisabled(String provider) {
        }
        @Override
        public void onLocationChanged(final Location location) {
        }
    });
4
  • HI Homescreen is what? is it application context?
    – Naruto
    Commented Jul 20, 2013 at 17:13
  • Yes, its the application context
    – Siddharth
    Commented Jul 21, 2013 at 12:55
  • 1
    HI, i re-booted my samsung phone, it automatically started working without any modification, i dont no what was the issue. Also one thing i noticed before re-booting is, it was working fine for default map application. I faced this issue only in my samsung s duos phone
    – Naruto
    Commented Jul 21, 2013 at 14:03
  • 1
    A reboot triggers a cache update. Test it after moving around a bit (100meters). Infact just create a timer to print current gps location every 5 seconds and move around your locality. DONT load google map app. Or any other map app. That will be the real test.
    – Siddharth
    Commented Jul 21, 2013 at 16:48
6

This is the exactly working solution, probaly in slight different circumstances. But I wanted to add some little explanation steps so that anybody gets the exact concepts:

1) onCreate() of Android Component (Eg, Activity, Fragment or Service. Note: Not IntentService), build and then connect the GoogleApiClient as below.

buildGoogleApiClient();
mGoogleApiClient.connect();

where, buildGoogleApiClient() implementation is,

protected synchronized void buildGoogleApiClient() {
        Log.i(TAG, "Building GoogleApiClient");

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addApi(LocationServices.API)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .build();

    }

Later on onDestroy(), you can disconnect GoogleApiClient as,

@Override
    public void onDestroy() {
        Log.i(TAG, "Service destroyed!");
        mGoogleApiClient.disconnect();
        super.onDestroy();
    }

The step 1 makes sure you build and connect the GoogleApiClient.

1) GoogleApiClient instance first time gets connected on method onConnected(). Now, your next step should look onConnected() method.

@Override
    public void onConnected(@Nullable Bundle bundle) {
        Log.i(TAG, "GoogleApiClient connected!");
        buildLocationSettingsRequest();
        createLocationRequest();
        location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        Log.i(TAG, " Location: " + location); //may return **null** because, I can't guarantee location has been changed immmediately 
    }

Above, you called a method createLocationRequest() to create location request. The method createLocationRequest() looks like below.

protected void createLocationRequest() {
        //remove location updates so that it resets
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this); //Import should not be **android.Location.LocationListener**
    //import should be **import com.google.android.gms.location.LocationListener**;

        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(10000);
        mLocationRequest.setFastestInterval(5000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        //restart location updates with the new interval
        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);

    }

3) Now, on onLocationChange() callback of LocationListener interface, you get new location.

@Override
    public void onLocationChanged(Location location) {
        Log.i(TAG, "Location Changed!");
        Log.i(TAG, " Location: " + location); //I guarantee,I get the changed location here

    }

You get the result like this in Logcat: 03-22 18:34:17.336 817-817/com.LiveEarthquakesAlerts I/LocationTracker: Location: Location[fused 37.421998,-122.084000 acc=20 et=+15m35s840ms alt=0.0]

To be able to do these three steps, you should have configured your build.gradle as below:

 compile 'com.google.android.gms:play-services-location:10.2.1'
1
  • 1
    Can you post the code for your buildLocationSettingsRequest() method? Commented Oct 18, 2018 at 19:51
5

You must check if user has enabled location via Wi-Fi/GSM or GPS. If there isn't any available location provider, you get null.

This code displays the screen with location settings:

startActivity(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS));
1
  • the local settings looks good. it just seems that i have to wait for the location changing —— thanks a lot Commented May 30, 2013 at 17:19
3

On SDK versions 23

You will also need to explicitly request the location permission during runtime, as per https://developer.android.com/training/permissions/requesting.html as well as having it in the manifest file.

No explicit error will occur if you do not have the permissions during runtime, the location provider will just return null.

It would help if Google documented this, and also throw an exception rather than just returning null. Returning null is about the least helpful thing to do in this situation.

1
  • 1
    Or you can grant permission from app settings explicitly Commented Oct 16, 2016 at 15:37
2

I was also facing the same issue on my app, and the only missing thing was that the app only requested for ACCESS_COARSE_LOCATION and not ACCESS_FINE_LOCATION. I added the later permission and everything worked OK.

1

You just need an update request for the location. If with 26 Android SDK permitions is all ok:

private void setLocation(Context context) {
    GoogleApiClient googleApiClient = new GoogleApiClient.Builder(context)
            .addApi(LocationServices.API).build();
    googleApiClient.connect();

     locationRequest = LocationRequest.create();
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    locationRequest.setInterval(2000);
    locationRequest.setFastestInterval(2000);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder().addLocationRequest(locationRequest);
    builder.setAlwaysShow(true);
    PendingResult<LocationSettingsResult> result = LocationServices.SettingsApi.checkLocationSettings(googleApiClient, builder.build());
    result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
        @Override
        public void onResult(LocationSettingsResult result) {
            final Status status = result.getStatus();
            switch (status.getStatusCode()) {
                case LocationSettingsStatusCodes.SUCCESS:
                    showMessage(" All location settings are satisfied.");
                    mGoogleApiClient = new GoogleApiClient.Builder(MainActivity.this)
                            .addApi(LocationServices.API)
                            .addConnectionCallbacks(connectionCallbacks)
                            .addOnConnectionFailedListener(connectionFailedListener)
                            .build();
                            mGoogleApiClient.connect();
                    break;
                case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
                    l.a(" Location settings are not satisfied. Show the user a dialog to upgrade location settings ");

                    try {
                        // Show the dialog by calling startResolutionForResult(), and check the result
                        // in onActivityResult().
                        status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
                    } catch (IntentSender.SendIntentException e) {
                        showMessage("PendingIntent unable to execute request.");
                    }
                    break;
                case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
                    showMessage("Location settings are inadequate, and cannot be fixed here. Dialog not created.");
                    break;
            }
        }
    });
}

and in onConnected callback method:

 @Override
    public void onConnected(@Nullable Bundle bundle) {
        l.a(3232);
        if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) !=
                PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                   return;
        }

            mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                    mGoogleApiClient);
       if(null==mLastLocation){//  !!!!!!!!!!!! here it can happen !!!!!!!

                    LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, locationRequest, new LocationListener() {
                        @Override
                        public void onLocationChanged(Location location) {
                            mLastLocation = location;
                            locationWasFound = true;
                            sevumPora.setLocation(mLastLocation);
                            mGoogleApiClient.disconnect();
                        }
                    });
                return;
            }
        locationWasFound = true;
        sevumPora.setLocation(mLastLocation);
        mGoogleApiClient.disconnect();
    }
0

I run and its working perfect in Nexus 7 device. You guys by mistake written old version LocationListener which is not used with new API.

You have to set with new LocationListener.

You need to import this class and then try.

import com.google.android.gms.location.LocationListener;

And it override the only one method as per new API

@Override
public void onLocationChanged(final Location newLocation) 
{}

Please try this way and let me know if you still facing any issue.

Thanks.

0

Google play service geolocation can't work without internet connection, indifferently for GPS. So, please check app with mobile data switched on.

-3

The easiest fix, albeit slows it down a little, is to use a helper function. My problem was that it would connect, but before there was a location found, I would try to access it and hit a null pointer.

public Location getLocation(LocationClient locationClient){

    if(locationClient.getLastLocation() == null){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return getLocation(locationClient);
    }else{
        return locationClient.getLastLocation();
    }
}

Just use this in onConnected and set whatever you wanted the location to be using this function, passing your location client.

@Override
public void onConnected(Bundle dataBundle) {

    Location temp = getLocation(mLocationClient);
    mLocation = temp;
}

Also if you don't want to get the location from onConnected for whatever reason, you can use the same helper function anywhere as long as you pass your locationClient.

1
  • You're stacking a recursive call on getLocation every second?. That's not good.
    – Mar Bar
    Commented Dec 17, 2015 at 20:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.