getLastLocation sometimes returns null

Asked

Viewed 63 times

2

I use the following code to get the user’s location:

@Override
  protected void onCreate(Bundle savedInstanceState)
  {
    super.onCreate(savedInstanceState);

    ...

    m_api = new GoogleApiClient.Builder(context)
                    .addConnectionCallbacks(this)
                    .addApi(LocationServices.API)
                    .build();

    ...

  }    

  @Override
  protected void onStart()
  {
    super.onStart();
    m_api.connect();
  }

  @Override
  protected void onStop()
  {
    m_api.disconnect();
    super.onStop();
  }

  @Override
  public void onConnected(Bundle bundle)
  {
    Address address;
    Location cur = LocationServices.FusedLocationApi.getLastLocation(m_api);

    Geocoder geocoder;
    List<Address> addressList;

    geocoder = new Geocoder(this, Locale.getDefault());
    addressList = geocoder.getFromLocation(cur.getLatitude(),cur.getLongitude(), 1);

    if (addressList != null && !addressList.isEmpty()) {
      address = addressList.get(0);

      ...
    }
  }

Of the five devices I tested, three worked and two didn’t. In both, which did not work, the "getLastLocation" method returned null and aborts execution.

I’ve put in the app dependences 'com.google.android.gms:play-services-Location:9.4.0'. I’m using the minSdkVersion 16 compatibility API.

Of the two devices that aborted the run one had android 4.4 and other 5.1.

Have some coding error?

Does the problem lie in the API installed on the device? How to test?

  • Physical devices or emulators?

  • Physical devices.

  • I checked the post, but the problem is as times getLastLocation returns null.

  • This is possible, you have to deal with this situation when it occurs. See this

  • I was able to solve it. On some devices, getLastLocation returns null. Please remove the duplicate so that I can post the solution. And, if possible, change the text "marked as duplicate".

  • 1

    If you have an answer you should put it in this question which is the question that starts the duplicate chain.

  • The question does not deal with the return null method on certain devices. Anyway it is possible to "... handle this situation when it occurs." (@ramaral). I close here.

Show 2 more comments

1 answer

0

Try to follow this Tutorial.

The solution is to replace in your Androidmanifest.xml

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

for

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
  • I have these two <uses-permission> in the manifest. But, in the tutorial link when called the getLastLocation method it checks if the result is != null, it remains to be seen in what situations the return can be null.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.