我刚刚开始工作,但是当我关闭我的 Wifi 以查看是否可以使用我的 GPS 获得更准确的位置时,它现在给我带来了一个NullPointer
错误,我不明白为什么。
下面的代码首先被调用;
public void onConnected(Bundle dataBundle) {
connected = true;
//Request an update from the location client to get current Location details
mLocationClient.requestLocationUpdates(mLocationRequest,this);
Toast.makeText(this, "Connected", Toast.LENGTH_SHORT).show();
}
然后需要调用此方法
public void onLocationChanged(android.location.Location location) {
// Report to the UI that the location was updated
String msg = "Updated Location: " +
Double.toString(location.getLatitude()) + "," +
Double.toString(location.getLongitude());
if(tmp != location.getLatitude())
{
Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
}
tmp = location.getLatitude();
}
您可以看到我在那里有 2 个祝酒词,它们以实际的 GPS 坐标返回,但是当我调用下面的代码时,它在新的位置线上崩溃了getLastKnownLocation
public String getLocation()
{
// Get the location manager
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
Criteria criteria = new Criteria();
String bestProvider = locationManager.getBestProvider(criteria, false);
android.location.Location location = locationManager.getLastKnownLocation(bestProvider);
Double lat,lon;
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
try {
lat = location.getLatitude ();
lon = location.getLongitude ();
Toast.makeText(this,""+lat.toString()+"-"+lon.toString(),Toast.LENGTH_SHORT).show();
return new LatLng(lat, lon).toString();
}
catch (NullPointerException e){
Toast.makeText(this,"HELL-NO",Toast.LENGTH_SHORT).show();
Log.e("HELL-NO","n",e);
e.printStackTrace();
return null;
}
}
我只是不明白为什么当我尝试检索似乎已在onLocationChanged
方法中检索到的位置时,它只是提出了一个空指针。