Tony Chhabada
Tony Chhabada

Reputation: 412

Sleep in For loop

I am developing a simple game. I want to have small wait in each interation of a for loop that will be executed on button click.

I have tried using Thread.sleep(2000), but to no avail.

Here is the code of button click:

public void playClick(View v) {
        String item;
        try{
            final Handler handler = new Handler();
        for (int i = 0; i < stringList.size(); i++) {

             Thread.sleep(2000);
            item = stringList.get(i);

            if(item.equals("left")){

                leftclick();

            }else if(item.equals("right")){

                rightClick();

            }else if(item.equals("up")){

                upClick();

            }else if(item.equals("down")){

                downClick();

            }
        }
        }catch(Exception e){
            Toast.makeText(this, ""+e.toString(), Toast.LENGTH_SHORT).show();
        }

I want to wait in each execution of the for loop.

Upvotes: 1

Views: 283

Answers (2)

Igor Rodriguez
Igor Rodriguez

Reputation: 1246

An alternative to the solution by @Sam is to use javax.swing.Timer.

Upvotes: 0

Sam
Sam

Reputation: 86948

Blocking the main Thread is not recommended, instead I suggest creating a Runnable and passing it to your existing, unused Handler. Maybe:

private final Handler handler = new Handler();
private final Runnable runnable = new Runnable() {
    @Override
    public void run() {
        for (String item : stringList) {
            if(item.equals("left")){
                leftclick();
            }else if(item.equals("right")){
                rightClick();
            }else if(item.equals("up")){
                upClick();
            }else if(item.equals("down")){
                downClick();
            }
        }
    }
}

...

public void playClick(View v) {
    // Execute the code inside runnable in 2 seconds
    handler.postDelayed(runnable, 2000);
}

Upvotes: 6

Related Questions