user3214173
user3214173

Reputation: 227

iterate a thread/handler/timer 10 times

i want to iterate a thread 10 times..

 for(final int i: list)<-- problem
    {
        Timer timer = new Timer();
        TimerTask timertask = new TimerTask() {

            @Override
            public void run() {
                // TODO Auto-generated method stub
                imageView.setBackgroundResource(i);
            }
        };
        timer.schedule(timertask,200);  
    }

this code does that but eclipse recomends/insists on the i being final..

thus only last image is being displayed.. is there any way i can iterate this such that all images are displayed and timer can run correctly???

also pls dont recomend animation.. it has completely failed.. thats why i am resorting to this...

Upvotes: 0

Views: 122

Answers (2)

Jean Logeart
Jean Logeart

Reputation: 53809

Simply copy the value of i in a final variable:

for(int i : list) {
    final int value = i;
    Timer timer = new Timer();
    TimerTask timertask = new TimerTask() {
        @Override
        public void run() {
            imageView.setBackgroundResource(value);
        }
    };
    timer.schedule(timertask,200);  
}

Upvotes: 1

codeMagic
codeMagic

Reputation: 44571

To fix your code you could just use a local variable

for(int i: list)<-- problem no more
{
    Timer timer = new Timer();
    TimerTask timertask = new TimerTask() {

    // create a final variable and assign it to i
    final int x = i;

        @Override
        public void run() {
            // TODO Auto-generated method stub
            imageView.setBackgroundResource(x);   // then use it here
        }
    };
    timer.schedule(timertask,200);  
}

Upvotes: 2

Related Questions