我有一個Android應用程序,它是一個具有兩個按鈕的基本計時器,啓動和停止。每當我連續兩次按下停止按鈕時,應用程序將以空指針異常崩潰。Android定時器 - Java空指針異常
問題的方法是:
public void stopTimer(View view) {
timerTask.cancel();
timerTask = null;
n = 0;
}
的logcat如下:
01-27 20:43:01.173: E/dalvikvm(14195): could not disable core file generation for pid
14195: Operation not permitted
01-27 20:43:32.455: D/AndroidRuntime(14195): Shutting down VM
01-27 20:43:32.455: W/dalvikvm(14195): threadid=1: thread exiting with uncaught exception (group=0x40018560)
01-27 20:43:32.478: E/AndroidRuntime(14195): FATAL EXCEPTION: main
01-27 20:43:32.478: E/AndroidRuntime(14195): java.lang.IllegalStateException: Could not execute method of the activity
01-27 20:43:32.478: E/AndroidRuntime(14195): at android.view.View$1.onClick(View.java:2144)
01-27 20:43:32.478: E/AndroidRuntime(14195): at android.view.View.performClick(View.java:2485)
01-27 20:43:32.478: E/AndroidRuntime(14195): at android.view.View$PerformClick.run(View.java:9089)
01-27 20:43:32.478: E/AndroidRuntime(14195): at android.os.Handler.handleCallback(Handler.java:587)
01-27 20:43:32.478: E/AndroidRuntime(14195): at android.os.Handler.dispatchMessage(Handler.java:92)
01-27 20:43:32.478: E/AndroidRuntime(14195): at android.os.Looper.loop(Looper.java:123)
01-27 20:43:32.478: E/AndroidRuntime(14195): at android.app.ActivityThread.main(ActivityThread.java:3806)
01-27 20:43:32.478: E/AndroidRuntime(14195): at java.lang.reflect.Method.invokeNative(Native Method)
01-27 20:43:32.478: E/AndroidRuntime(14195): at java.lang.reflect.Method.invoke(Method.java:507)
01-27 20:43:32.478: E/AndroidRuntime(14195): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
01-27 20:43:32.478: E/AndroidRuntime(14195): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
01-27 20:43:32.478: E/AndroidRuntime(14195): at dalvik.system.NativeStart.main(Native Method)
01-27 20:43:32.478: E/AndroidRuntime(14195): Caused by: java.lang.reflect.InvocationTargetException
01-27 20:43:32.478: E/AndroidRuntime(14195): at java.lang.reflect.Method.invokeNative(Native Method)
01-27 20:43:32.478: E/AndroidRuntime(14195): at java.lang.reflect.Method.invoke(Method.java:507)
01-27 20:43:32.478: E/AndroidRuntime(14195): at android.view.View$1.onClick(View.java:2139)
01-27 20:43:32.478: E/AndroidRuntime(14195): ... 11 more
01-27 20:43:32.478: E/AndroidRuntime(14195): Caused by: java.lang.NullPointerException
01-27 20:43:32.478: E/AndroidRuntime(14195): at com.example.timer.MainActivity.stopTimer(MainActivity.java:56)
01-27 20:43:32.478: E/AndroidRuntime(14195): ... 14 more
01-27 20:43:35.564: I/Process(14195): Sending signal. PID: 14195 SIG: 9
01-27 20:48:05.103: D/dalvikvm(14263): GC_EXPLICIT freed 75K, 51% free 2682K/5379K, external 2357K/2773K, paused 23ms
有什麼我可以這樣做,如果用戶恰好按兩次在一排按鈕,應用程序不會崩潰在他們身上?就目前來看,一旦int值仍然顯示,如果他們按停止。也許如果停止被再次按下它可以重置爲0?
非常感謝您的任何建議/反饋。
'如果(TimerTask的!= NULL){//你已經擁有}'以前
timerTask
不爲空?關於int不重置的第二部分聽起來像一個單獨的問題,其中值未在UI上更新。 – turbo