I want to get address City Name and then put it in String, and user should turn on GPS first. I've tried many code but nothing happended. Until I found this, and I following JavaVersion from this answear to get latitude and longitude.
private final String TAG = "MainActivity";
private FusedLocationProviderClient fusedLocationClient;
private final CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
....
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
....
fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
....
buttonGetLocation.setOnClickListener(view -> {
requestCurrentLocation()
}
....
}
private void requestCurrentLocation() {
Log.d(TAG, "requestCurrentLocation()");
// Request permission
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
// Main code
Task<Location> currentLocationTask = fusedLocationClient.getCurrentLocation(
PRIORITY_HIGH_ACCURACY,
cancellationTokenSource.getToken()
);
currentLocationTask.addOnCompleteListener((new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
String result = "";
if (task.isSuccessful()) {
// Task completed successfully
Location location = task.getResult();
result = "Location (success): " +
location.getLatitude() +
", " +
location.getLongitude();
getAddress(location.getLatitude(), location.getLongitude()); // Get Address
} else {
// Task failed with an exception
Exception exception = task.getException();
result = "Exception thrown: " + exception;
}
Log.d(TAG, "getCurrentLocation() result: " + result);
}
}));
} else {
// TODO: Request fine location permission
Log.d(TAG, "Request fine location permission.");
}
}
private void getAddress(double LATITUDE, double LONGITUDE) {
//Set Address
Geocoder geocoder = new Geocoder(this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
} catch (IOException e) {
e.printStackTrace();
}
if (addresses != null && addresses.size() > 0) {
String address = addresses.get(0).getAddressLine(0); // If any additional address line present than only, check with max available address lines by getMaxAddressLineIndex()
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knownName = addresses.get(0).getFeatureName(); // Only if available else return NULL
Log.d(TAG, "getAddress: address" + address);
Log.d(TAG, "getAddress: city" + city);
Log.d(TAG, "getAddress: state" + state);
Log.d(TAG, "getAddress: postalCode" + postalCode);
Log.d(TAG, "getAddress: knownName" + knownName);
} else {
Log.d(TAG, "Fail get Location!");
}
}
but then I got this Location.getLatitude() on a null object reference :
java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a null object reference
at com.yayco.rebahan.MainActivity$5.onComplete(MainActivity.java:453)
at com.google.android.gms.tasks.zzj.run(com.google.android.gms:play-services-tasks@@17.2.0:4)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:201)
at android.app.ActivityThread.main(ActivityThread.java:6810)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:547)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:873)
What i miss? Thanks for help.