好日子,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
非常感謝您的詳細解釋 –