0

I am developing an application in which I want to implement timer task to print a toast message every 5 seconds. The problem is my application crashes after 5 seconds when i run it.Below is part of my code please tell me where I am making mistakes and how can I 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 is where I start my 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 the timer, if it's not already null
    if (time != null) {
        time.cancel();
        time = null;

    }

   }
 }
Arun
  • 140
  • 3
  • 15

1 Answers1

1

you forgot to initialize handler, Just add below line in oncreate or startTimer();

handle = new Handler();

Or even in your case you can use,

runOnUiThread(new Runnable(){
            @Override
            public void run() {
                int duration = Toast.LENGTH_SHORT;
                Toast toast = Toast.makeText(getApplicationContext(),"Timer...", duration);
                toast.show();

            }
        });
Madhur
  • 3,303
  • 20
  • 29