好日子,getLatitude和getLongitude引发NullPointerException异常
请你解释一下我为什么getLongitude和getLatitude返回一个NullPointerException?
事实是这个问题已经解决了,但有一件事情是我的论文协调员可能会问的。情况是我必须得到用户当前的坐标(经度和纬度)。我决定使用FusedLocationClient.getLastLocation()来获得坐标。
mFusedLocationClient = getFusedLocationProviderClient(this);
//app already crashes once the line below is executed
mFusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location != null){
//myLocation is an instance variable of this class
myLocation = location;
}else{
Toast.makeText(PlaceCategoriesActivity.this, "Location fetch failed!", Toast.LENGTH_SHORT).show();
}
}
});
latitude = myLocation.getLatitude(); //this line throws NullPointerException
longitude = myLocation.getLongitude();
的应用程序似乎编译细但随后崩溃,在通过上myLocation.getLatiude()和myLocation.getLongititude()将一个断点调试检查,事实证明,这种方法调用一个空指针异常,这对我来说很奇怪,因为myLocation已经引用了addOnSuccessListener的onSuccess方法所带来的位置对象。
mFusedLocationClient = getFusedLocationProviderClient(this);
mFusedLocationClient.getLastLocation().addOnSuccessListener(this, new OnSuccessListener<Location>() {
@Override
public void onSuccess(Location location) {
if(location != null){
myLocation = location;
//moved the 2 lines of code and it now works
latitude = myLocation.getLatitude();
longitude = myLocation.getLongitude();
}else{
Toast.makeText(PlaceCategoriesActivity.this, "Location fetch failed!", Toast.LENGTH_SHORT).show();
}
}
});
//Toast returns a value of 0 on latitude and 0 on longitude
Toast.makeText(this, "Lat: " + latitude + "Long: + " + longitude, Toast.LENGTH_SHORT).show();
有趣的是,经度和纬度显示在面包和:
我已经通过移动代码的最后两行和侦听器内投入这样的问题解决了既有的0
非常感谢您的详细解释 –