0

I have timer which schedules each 1 sec, and as we can't toast in timertask I used handler.post(). But this code breaks my app:

    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_game);

    handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            String text = (String) msg.obj;
            sec_view.setText(text);
        }
    };

    MyTimerTask myTask = new MyTimerTask();
    timer = new Timer();
    timer.schedule(myTask, 1000, 1000);
}

Runnable makeToast = new Runnable() {
    public void run() {
        Toast.makeText(null, "qwerty", Toast.LENGTH_LONG).show();
    }
};


class MyTimerTask extends TimerTask {
    public void run(){
        if(0 == --sec){
            handler.post(makeToast);  //breaks there
            timer.cancel();
        }
        Message msg = new Message();
        msg.obj = sec+" sekund";
        handler.sendMessage(msg);
    }
}

Can I use anything else to toast from timertask?

Kerim Amanov
  • 213
  • 3
  • 14

2 Answers2

1

currently you are passing null as Context in Toast.makeText.just pass context instead of null to show toast

Toast.makeText(Your_Activity.this, "qwerty", Toast.LENGTH_LONG).show();

and to show Toast or access UI elements from timertask run method use runOnUiThread() as

public void run() {
  Current_Activity.this.runOnUiThread(new Runnable() {
     @Override
     public void run() {
          //show your toast here
       }
    });
}
ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213
0

change toast to

Toast.makeText(getApplicationContext(), "qwerty", Toast.LENGTH_LONG).show();

then add @override annotation above void run in handler

Viswanath Lekshmanan
  • 9,945
  • 1
  • 40
  • 64