应用程序在启动时崩溃,出现空指针异常。当已经授予位置权限时,就会发生这种情况。但是,当未授予位置权限且仅在应用启动后才授予位置权限时,不会发生这种情况。
public void requestLocationUpdates() {
Log.i(TAG, "Requesting location updates");
Utils.setRequestingLocationUpdates(this, true);
startService(new Intent(getApplicationContext(),
LocationUpdatesService.class));
try {
mFusedLocationClient.requestLocationUpdates(mLocationRequest,
mLocationCallback, Looper.myLooper());
} catch (SecurityException unlikely) {
Utils.setRequestingLocationUpdates(this, false);
Log.e(TAG, "Lost location permission. Could not request updates. " +
unlikely);
}
}
下面是错误。
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.example.projectu/com.example.projectu.MainActivity}:
java.lang.NullPointerException: Attempt to invoke virtual method 'void
com.example.projectu.LocationUpdatesService.requestLocationUpdates()' on a
null object reference
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:440)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'void
com.example.projectu.LocationUpdatesService.requestLocationUpdates()' on a
null object reference
at com.example.projectu.MainActivity.onStart(MainActivity.java:265)
at
android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1334)
at android.app.Activity.performStart(Activity.java:7029)
at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2741)
答案 0 :(得分:0)
您尚未初始化mFusedLocationClient,并在空对象上调用其mFusedLocationClient.requestLocationUpdates