Damodar Dahal
Damodar Dahal

Reputation: 569

Timer not working properly android

I have a button that calls function beginMemoryQuest(View v). I was expecting a count-up of numbers of 0-5 with a difference of 1 second in each. Meaning, the Handler mHandler should be receiving index from 0-5. But, as it seems, the LogCat is printing that it is receiving all index=6 calls. How do I fix this? I want the Handler to receive calls from 0-6, each with a period of a second.

I appreciate any help, thank you very much!

private static int index;
public void beginMemoryQuest(View v){
    Timer t=new Timer();

    for(index=0;index<6;index++){
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                Bundle b=new Bundle();
                b.putInt("index", index);
                Message msg=new Message();
                msg.setData(b);
                mHandler.sendMessage(msg);
            }
        }, 1000*index+1);
    }
}
public Handler mHandler=new Handler(){
    public void handleMessage(Message msg){
        int ind=msg.getData().getInt("index", -1);
        Log.e("###","handling "+ind);
    }
};

PS: the Handler is has a warning: This Handler class should be static or leaks might occur

Upvotes: 1

Views: 1619

Answers (1)

Asif Mujteba
Asif Mujteba

Reputation: 4656

First problem is you are creating 6 timer tasks instead of just repeating same task 6 times. Secondly, The timer task is run after a delay, and by then you have created all 6 timer tasks and incremented the index value to 6 before even the task ever started.

Try something like this:

private int index = 0;
public void beginMemoryQuest(View v){
    final Timer t = new Timer();

    t.schedule(new TimerTask() {
        @Override
        public void run() {
            Bundle b=new Bundle();
            b.putInt("index", index);
            Message msg=new Message();
            msg.setData(b);
            mHandler.sendMessage(msg);
            index++;
            if (index>=6) {
                t.cancel();
            }
        }
    }, 1000, 1000);
}

Update: I have added a 3rd parameter to schedule method which lets timer know to schedule it again after specified delay, until we cancel the timer.

Upvotes: 2

Related Questions