以下用于推导经度和纬度的代码给了我一个 NPE
初始声明:
double longitude, latitude;
Location location;
LocationManager manager;
代码:
final LocationListener locationListener = new LocationListener(){
@Override
public void onLocationChanged(Location arg0) {
// TODO Auto-generated method stub
latitude = location.getLatitude();
longitude = location.getLongitude();
}
@Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String arg0, int arg1,
Bundle arg2) {
// TODO Auto-generated method stub
}
};
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2000, 10, locationListener);
location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
longitude = location.getLongitude();
latitude = location.getLatitude();
Toast.makeText(getApplicationContext(), "lat and lon"+latitude+" "+longitude, Toast.LENGTH_LONG).show();
NPE发生在
longitude = location.getLongitude(); //Line 91
日志猫:
09-01 09:58:27.689: D/AndroidRuntime(3073): Shutting down VM
09-01 09:58:27.689: W/dalvikvm(3073): threadid=1: thread exiting with uncaught exception (group=0x40df98a8)
09-01 09:58:27.749: E/AndroidRuntime(3073): FATAL EXCEPTION: main
09-01 09:58:27.749: E/AndroidRuntime(3073): java.lang.NullPointerException
09-01 09:58:27.749: E/AndroidRuntime(3073): at com.vaw.selfhelp.SmsActivity$2.onClick(SmsActivity.java:91)
09-01 09:58:27.749: E/AndroidRuntime(3073): at android.view.View.performClick(View.java:4091)
09-01 09:58:27.749: E/AndroidRuntime(3073): at android.view.View$PerformClick.run(View.java:17072)
09-01 09:58:27.749: E/AndroidRuntime(3073): at android.os.Handler.handleCallback(Handler.java:615)
09-01 09:58:27.749: E/AndroidRuntime(3073): at android.os.Handler.dispatchMessage(Handler.java:92)
09-01 09:58:27.749: E/AndroidRuntime(3073): at android.os.Looper.loop(Looper.java:153)
09-01 09:58:27.749: E/AndroidRuntime(3073): at android.app.ActivityThread.main(ActivityThread.java:4987)
09-01 09:58:27.749: E/AndroidRuntime(3073): at java.lang.reflect.Method.invokeNative(Native Method)
09-01 09:58:27.749: E/AndroidRuntime(3073): at java.lang.reflect.Method.invoke(Method.java:511)
09-01 09:58:27.749: E/AndroidRuntime(3073): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:821)
09-01 09:58:27.749: E/AndroidRuntime(3073): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:584)
09-01 09:58:27.749: E/AndroidRuntime(3073): at dalvik.system.NativeStart.main(Native Method)
使用以下权限:
<uses-permission android:name="android.permission.CALL_PHONE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.SEND_SMS"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>