Implementing a while loop in android Implementing a while loop in android android android

Implementing a while loop in android


Brace yourself. And try to follow closely, this will be invaluable as a dev.

While loops really should only be implemented in a separate Thread. A separate thread is like a second process running in your app. The reason why it force closed is because you ran the loop in the UI thread, making the UI unable to do anything except for going through that loop. You have to place that loop into the second Thread so the UI Thread can be free to run. When threading, you can't update the GUI unless you are in the UI Thread. Here is how it would be done in this case.

First, you create a Runnable, which will contain the code that loops in it's run method. In that Runnable, you will have to make a second Runnable that posts to the UI thread. For example:

 TextView myTextView = (TextView) findViewById(R.id.myTextView); //grab your tv Runnable myRunnable = new Runnable() {      @Override      public void run() {           while (testByte == 0) {                Thread.sleep(1000); // Waits for 1 second (1000 milliseconds)                String updateWords = updateAuto(); // make updateAuto() return a string                myTextView.post(new Runnable() {                      @Override                     public void run() {                          myTextView.setText(updateWords);                     });           }      } };

Next just create your thread using the Runnable and start it.

 Thread myThread = new Thread(myRunnable); myThread.start();

You should now see your app looping with no force closes.


You can create a new Thread for a while loop.

This code will create a new thread to wait for a boolean value to change its state.

private volatile boolean isClickable = false;new Thread() {    @Override    public void run() {        super.run();        while (!isClickable) {            // boolean is still false, thread is still running        }        // do your stuff here after the loop is finished    }}.start();