我在这一行收到一个空指针异常:
double latitude = location.getLatitude();
我需要做些什么来初始化我的 Location 变量吗?我究竟做错了什么?
这是我的源代码:
Location location;
if (isGpsEnabled) {
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
else {
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
}
Log.i(TAG, "Provider is: "+provider);
Log.i(TAG, "Location is: "+location);
//Zooms into the current location when the activity is started
double latitude = location.getLatitude();
double longitude = location.getLongitude();
这是我收到的 logcat 输出:
06-17 09:22:40.797: E/AndroidRuntime(12436): FATAL EXCEPTION: main
06-17 09:22:40.797: E/AndroidRuntime(12436): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.android.gpstracker/com.polaris.epicriders.Rides.RideTracking}: java.lang.NullPointerException
06-17 09:22:40.797: E/AndroidRuntime(12436): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
06-17 09:22:40.797: E/AndroidRuntime(12436): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
06-17 09:22:40.797: E/AndroidRuntime(12436): at android.app.ActivityThread.access$600(ActivityThread.java:141)
06-17 09:22:40.797: E/AndroidRuntime(12436): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
06-17 09:22:40.797: E/AndroidRuntime(12436): at android.os.Handler.dispatchMessage(Handler.java:99)
06-17 09:22:40.797: E/AndroidRuntime(12436): at android.os.Looper.loop(Looper.java:137)
06-17 09:22:40.797: E/AndroidRuntime(12436): at android.app.ActivityThread.main(ActivityThread.java:5041)
06-17 09:22:40.797: E/AndroidRuntime(12436): at java.lang.reflect.Method.invokeNative(Native Method)
06-17 09:22:40.797: E/AndroidRuntime(12436): at java.lang.reflect.Method.invoke(Method.java:511)
06-17 09:22:40.797: E/AndroidRuntime(12436): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
06-17 09:22:40.797: E/AndroidRuntime(12436): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
06-17 09:22:40.797: E/AndroidRuntime(12436): at dalvik.system.NativeStart.main(Native Method)
06-17 09:22:40.797: E/AndroidRuntime(12436): Caused by: java.lang.NullPointerException
06-17 09:22:40.797: E/AndroidRuntime(12436): at com.polaris.epicriders.Rides.RideTracking.onCreate(RideTracking.java:273)
06-17 09:22:40.797: E/AndroidRuntime(12436): at android.app.Activity.performCreate(Activity.java:5104)
06-17 09:22:40.797: E/AndroidRuntime(12436): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
06-17 09:22:40.797: E/AndroidRuntime(12436): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
06-17 09:22:40.797: E/AndroidRuntime(12436): ... 11 more