我启动应用程序,当我按下后退按钮时,我收到以下logcat错误。广播接收器在onStart中注册,在onStop中未注册。
请让mek知道我收到此错误的原因?
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
Log.w(TAG, LogAnd.show("onStop", ""));
if ((asyncDis != null) && (asyncDis.getStatus() == AsyncTask.Status.PENDING) || (asyncDis.getStatus() == AsyncTask.Status.RUNNING) ) {
asyncDis.cancel(true);
Log.d(TAG, LogAnd.show("onStop", "AsyncTask Cancelled."));
}
unregisterReceiver(btReceiver);
Log.d(TAG, LogAnd.show("onStop", "BT-Receiver unregistered"));
}
logcat的:
08-28 14:55:40.811: E/AndroidRuntime(4542): FATAL EXCEPTION: main
08-28 14:55:40.811: E/AndroidRuntime(4542): Process: com.example.bt_04, PID: 4542
08-28 14:55:40.811: E/AndroidRuntime(4542): java.lang.RuntimeException: Unable to stop activity {com.example.bt_04/com.example.bt_04.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.AsyncTask$Status com.example.bt_04.MainActivity$AsyncDiscovery.getStatus()' on a null object reference
08-28 14:55:40.811: E/AndroidRuntime(4542): at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:4150)
08-28 14:55:40.811: E/AndroidRuntime(4542): at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:4213)
08-28 14:55:40.811: E/AndroidRuntime(4542): at android.app.ActivityThread.access$1500(ActivityThread.java:177)
08-28 14:55:40.811: E/AndroidRuntime(4542): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1502)
08-28 14:55:40.811: E/AndroidRuntime(4542): at android.os.Handler.dispatchMessage(Handler.java:102)
08-28 14:55:40.811: E/AndroidRuntime(4542): at android.os.Looper.loop(Looper.java:145)
08-28 14:55:40.811: E/AndroidRuntime(4542): at android.app.ActivityThread.main(ActivityThread.java:5938)
08-28 14:55:40.811: E/AndroidRuntime(4542): at java.lang.reflect.Method.invoke(Native Method)
08-28 14:55:40.811: E/AndroidRuntime(4542): at java.lang.reflect.Method.invoke(Method.java:372)
08-28 14:55:40.811: E/AndroidRuntime(4542): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1400)
08-28 14:55:40.811: E/AndroidRuntime(4542): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1195)
08-28 14:55:40.811: E/AndroidRuntime(4542): Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.AsyncTask$Status com.example.bt_04.MainActivity$AsyncDiscovery.getStatus()' on a null object reference
08-28 14:55:40.811: E/AndroidRuntime(4542): at com.example.bt_04.MainActivity.onStop(MainActivity.java:612)
答案 0 :(得分:2)
您将获得NPE
:
asyncDis.getStatus();
您可以这样做:
@Override
protected void onStop() {
Log.w(TAG, LogAnd.show("onStop", ""));
if(asyncDis != null){
if(asyncDis.getStatus() != null) {
if (asyncDis.getStatus() == AsyncTask.Status.PENDING)||
(asyncDis.getStatus() == AsyncTask.Status.RUNNING) {
asyncDis.cancel(true);
Log.d(TAG, LogAnd.show("onStop", "AsyncTask Cancelled."));
}
}
}
super.onStop();
}