Search code examples
javaandroidtoast

Why does Toast skip to last element within this loop?


I'm practicing using Android Studio, so I'm making a very basic program where the user clicks on a button, and a Toast message will go through each element within an array tied to that button using a for loop. For some reason, this only shows me the last element within the array. I've tested to see if, individually, everything can be called, and there is no issue there, but the for loop will only show me the last element. Is this simply how toasts work, or am I missing something?

    public void select(View v) {
    String tester = v.getTag().toString();

    if (tester.equals("Stage_01")) {
        for (int x = 0; x < stage_01.enemyList.length; x++) {
            Toast.makeText(this, "Monsters in stage 1: " + stage_01.enemyList[x], Toast.LENGTH_SHORT).show();
        }
    }
}

Solution

  • The toast messages actually stacks up when it is used inside a for loop and what i experienced is a small delay in the messages. But if you want to clarify whether the for loop traverses through the array.

    1. You can put a System.out.println("Monsters in stage 1: " + stage_01.enemyList[x]); inside the for loop. You could see the output in the run tab in android studio.
    2. You can put a Log.d("TAG", "Monsters in stage 1: " + stage_01.enemyList[x]); inside the for loop. You could see the output in the logger tab in android studio.

    Both these tabs are located at the bottom of android studio.

    Hope this answer will help you clarify whether traversing works and the output is shown correctly.