我有一个正在运行的计时器,然后它会关闭并执行一些操作,并且计时器可以正常启动。
然后我想做的是单击一个按钮,然后让它创建一封电子邮件。一切正常,除了在计时器运行时单击按钮时,应用程序正在崩溃。当按下按钮时试图取消计时器时,这也会导致应用程序崩溃。
任何帮助,将不胜感激。
这是代码片段:
public class myApplication extends Activity {
StringBuilder str;
Timer t;
Button mailbutton;
public void onCreate(Bundle savedInstanceState) {
final StringBuilder str = new StringBuilder(1000);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
addListenerOnButton();
TimerTask task = new TimerTask() {
@Override
public void run()
{
/// do stuff here
}
}
t = new Timer();
t.schedule(task,2000,2000);
}
public void addListenerOnButton() {
mailbutton = (Button) findViewById(R.id.emailbutton);
mailbutton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
t.cancel();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"email@domain.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject");
i.putExtra(Intent.EXTRA_TEXT , str.toString());
try {
startActivity(Intent.createChooser(i, "Send mail"));
} catch (android.content.ActivityNotFoundException ex) {
}
}
});
}
}
LogCat 输出:
04-19 09:13:11.143: W/dalvikvm(12613): threadid=1: thread exiting with uncaught exception (group=0x40c421f8)
04-19 09:13:11.148: E/AndroidRuntime(12613): FATAL EXCEPTION: main
04-19 09:13:11.148: E/AndroidRuntime(12613): java.lang.NullPointerException
04-19 09:13:11.148: E/AndroidRuntime(12613): at uk.co.application.applicationActivity$2.onClick(applicationActivity.java:94)
04-19 09:13:11.148: E/AndroidRuntime(12613): at android.view.View.performClick(View.java:3591)
04-19 09:13:11.148: E/AndroidRuntime(12613): at android.view.View$PerformClick.run(View.java:14263)
04-19 09:13:11.148: E/AndroidRuntime(12613): at android.os.Handler.handleCallback(Handler.java:605)
04-19 09:13:11.148: E/AndroidRuntime(12613): at android.os.Handler.dispatchMessage(Handler.java:92)
04-19 09:13:11.148: E/AndroidRuntime(12613): at android.os.Looper.loop(Looper.java:137)
04-19 09:13:11.148: E/AndroidRuntime(12613): at android.app.ActivityThread.main(ActivityThread.java:4507)
04-19 09:13:11.148: E/AndroidRuntime(12613): at java.lang.reflect.Method.invokeNative(Native Method)
04-19 09:13:11.148: E/AndroidRuntime(12613): at java.lang.reflect.Method.invoke(Method.java:511)
04-19 09:13:11.148: E/AndroidRuntime(12613): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
04-19 09:13:11.148: E/AndroidRuntime(12613): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
04-19 09:13:11.148: E/AndroidRuntime(12613): at dalvik.system.NativeStart.main(Native Method)