android - Implementing Timer Task makes the application to crash -


i developing application in want implement timer task print toast message every 5 seconds. problem application crashes after 5 seconds when run it.below part of code please tell me making mistakes , how can overcome it.

public class main_activity extends activity implements bluetoothleuart.callback{  public imagebutton fabbutton; activity activity; timer time; timertask timetask; handler handle;  @override protected void oncreate(bundle savedinstancestate) {     super.oncreate(savedinstancestate);     setcontentview(r.layout.activity_main_activity);      fabbutton = (imagebutton) findviewbyid(r.id.fabbutton);    starttimer(); //this start timer task      fabbutton.setonclicklistener(new view.onclicklistener() {         @override         public void onclick(view v) {             scanledevice(false);             intent intent = new intent(getapplicationcontext(), scanlist.class);             startactivity(intent);          }      });  }   public void starttimer(){     time = new timer();     initializetimertask();     time.schedule(timetask, 5000, 10000);  } public void initializetimertask(){     timetask = new timertask() {         @override         public void run() {             handle.post(new runnable() {                 @override                 public void run() {                     int duration = toast.length_short;                     toast toast = toast.maketext(getapplicationcontext(),"timer...", duration);                     toast.show();                  }             });         }     }; } public void stoptimertask() {     //stop timer, if it's not null     if (time != null) {         time.cancel();         time = null;      }     }  } 

you forgot initialize handler, add below line in oncreate or starttimer();

handle = new handler(); 

or in case can use,

runonuithread(new runnable(){             @override             public void run() {                 int duration = toast.length_short;                 toast toast = toast.maketext(getapplicationcontext(),"timer...", duration);                 toast.show();              }         }); 

Comments