Reputation: 187
I have this method that I am calling in the onCreate()
and onResume()
methods in my MainActivity
.
Basically, I'm using it so I can get the city name of my current location and set it to a string so I can use it later. And to see if it worked I just set it to my welcome text.
The method is:
private void getLocation() {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
fusedLocationProviderClient.getLastLocation().addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
Location location = task.getResult();
if (location != null) {
try {
Geocoder geocoder = new Geocoder(MainActivity.this, Locale.getDefault());
List<Address> addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
cityName = addresses.get(0).getLocality(); // sets the address here
Welcome.setText(cityName);
} catch (IOException e) {
e.printStackTrace();
}
} else {
Toast.makeText(MainActivity.this, "Location null error", Toast.LENGTH_SHORT).show();
}
}
});
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[] {Manifest.permission.ACCESS_FINE_LOCATION},44);
}
}
Thing is, when I'm on the the android studio emulator, it works fine in most cases.
But when I'm running the app on my phone I get the "location null error" toast I have set up. Meaning location is null. Even when location is turned on in the device settings.
I can't figure out what the problem is.
Upvotes: 1
Views: 919
Reputation: 435
In your case, you want to use your geocoder inside the locationupdates method. Once the location is not null use that location to find your address then stop the updates.
For this you need to use requestLocationUpdates because lastKnownlocation could be null if the location was not requested in a certain amount of time by another application.
Take a look at my answer in this question. It will help you to get a location by using location updates
Upvotes: 3