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?
– ramaral
Physical devices.
– Edson Santos
I checked the post, but the problem is as times getLastLocation returns null.
– Edson Santos
This is possible, you have to deal with this situation when it occurs. See this
– ramaral
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".
– Edson Santos
If you have an answer you should put it in this question which is the question that starts the duplicate chain.
– ramaral
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.
– Edson Santos