Sami Varis Sami Varis - 2 months ago 16
Android Question

Android runOnUiThread not executing

I have this problem. I'm trying to update my

TextView
from another thread and it's not letting me.

I have tried a bunch of different solutions and none of those didn't seem to help. In my while loop code is printing that "Started new loop" all the time but it's not continuing from that
runOnUiThread
.

Can anyone help me figure out how to update
TextView
from another thread?

//second thread
protected void startKakkosThread() {
Thread t2 = new Thread() {
public void run() {
while (true) {
System.out.println("Started new loop");
runOnUiThread(new Runnable() {
@Override
public void run() {
try {
if(rullaavaNumero >= 0) {
rullaavaNumero--;
System.out.println(rullaavaNumero);
pelaajanPisteetTeksi.setText("" + rullaavaNumero);
sleep(1000);
}else{
rullaavaNumero = 9;
System.out.println(rullaavaNumero);
pelaajanPisteetTeksi.setText("" + rullaavaNumero);
sleep(1000);
}
}catch (InterruptedException e){
e.printStackTrace();
}
}
});
}
}
};
t2.start();
}

Answer

Here is a quick fix. Your sleep inside a Thread won't work like this. You want to delay your while loop, therefore call the delay out in your while loop. Then your code would look like this:

protected void startKakkosThread() {
    Thread t2 = new Thread() {
        public void run() {
            while (true) {
                System.out.println("Started new loop");
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (rullaavaNumero >= 0) {
                            rullaavaNumero--;
                            System.out.println(rullaavaNumero);
                            pelaajanPisteetTeksi.setText("" + rullaavaNumero);
                        } else {
                            rullaavaNumero = 9;
                            System.out.println(rullaavaNumero);
                            pelaajanPisteetTeksi.setText("" + rullaavaNumero);
                        }
                    }
                });
                try {
                    sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    };
    t2.start();
}

I have test it and it works, you could also go what @cricket has suggest.

My eye saw another thing which is not a part of your question, but good to mention. I assume you want to count from 9 to 0, it that the case, you need to correct following line by removing = otherwise you get counts till -1, so your code line would look like this:

if(rullaavaNumero > 0) {...