[英]FusedLocationProviderClient : Location.getLatitude() on a null object reference
I want to get address City Name and then put it in String, and user should turn on GPS first.我想得到地址 City Name 然后把它放在 String 中,用户应该先打开 GPS。 I've tried many code but nothing happended.我尝试了很多代码,但没有发生任何事情。 Until I found this, and I following JavaVersion from this answear to get latitude and longitude.直到我发现这个,我从这个答案中遵循JavaVersion来获取纬度和经度。
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:但后来我在 null object 参考上得到了这个 Location.getLatitude() :
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.感谢帮助。
you can try this code, it works for me:你可以试试这个代码,它对我有用:
private LocationRequest mLocationRequest;
mLocationRequest = LocationRequest.create();
private void requestCurrentLocation() {
Log.d(TAG, "requestCurrentLocation()");
// Request permission
if (ActivityCompat.checkSelfPermission(
this,
Manifest.permission.ACCESS_FINE_LOCATION) ==
PackageManager.PERMISSION_GRANTED) {
// Main code
fusedLocationClient.getLastLocation()
.addOnSuccessListener(new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
// GPS location can be null if GPS is switched off
if (location != null) {
getLocation(location);
} else {
if (ContextCompat.checkSelfPermission(mContext, android.Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
PermissionUtils.requestPermission((AppCompatActivity) mContext,
LOCATION_PERMISSION_REQUEST_CODE, Manifest.permission.ACCESS_FINE_LOCATION, false);
}
fusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, null);
}
}
})
.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
Log.e(TAG, "Error trying to get last GPS location");
e.printStackTrace();
}
});
} else {
// TODO: Request fine location permission
Log.d(TAG, "Request fine location permission.");
}
}
private final LocationCallback mLocationCallback = new LocationCallback() {
@Override
public void onLocationResult(LocationResult locationResult) {
super.onLocationResult(locationResult);
if (locationResult.getLastLocation() == null) {
//Log.e(TAG, "onLocationResult: null");
return;
}
getLocation(locationResult.getLastLocation());
}
};
private void getLocation(Location location){
//you will get location here
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.