Skip to content
Advertisement

Do a task with interval in a loop

I already saw many question here but nothing worked for me. I wanted to set the text in a text view after every 1 second. This is what I tried:

List<Integer> numbers = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = findViewById(R.id.ds);

        for (int i = 1; i < 90; i++) {
            numbers.add(i);
        }

        Collections.shuffle(numbers);

        for (int i = 0; i < numbers.size(); i++) {
            textView.setText(i + "");
        }




    }

This does the task immediately and only the last number is seen. Then this:

    List<Integer> numbers = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView textView = findViewById(R.id.ds);

        for (int i = 1; i < 90; i++) {
            numbers.add(i);
        }

        Collections.shuffle(numbers);

        for (int i = 0; i < numbers.size(); i++) {
            textView.setText(i + "");

            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

in this the screen shows blank white and after 90 seconds, I see the last number.

So, how can I achieve it?

Advertisement

Answer

Neither of these will work. In order to draw, the main thread must return to the Looper in the framework to handle draw commands. In other words, it can’t draw until onCreate exists. That means your first version will only draw the final time. The second would also only draw the final time, but may actually crash because you’re spending too long on the main thread without finishing (you should NEVER sleep on the main thread).

The solution is to use some sort of timer mechanism and draw on that. Examples of this would be TimerTask, or posting a message to a Handler and setting the text in that.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement