woske woske - 4 months ago 8
Android Question

TextView in thread error

I have the below code:

new Thread(new Runnable(){
public void run(){
try {
pos = Calculo.Calcular();
mostrarFrases(pos);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start();


where mostrarFrases is:

void mostrarFrases(int pos){

Mostrar = (TextView) findViewById(R.id.Texto);
Mostrar.setText(Frases[pos*2+1], 0, Frases[pos*2+1].length);
}


It works if i haven't any thread but without it does not work. I need thread because i need to wait until Calculo.Calcular() finish its work.

Answer

Rule: You cannot manipulate UI elements outside the UI thread.

Here is the proper way to do things:

//Asuming that your activiy is named MainActivity

        new Thread(new Runnable() {
            public void run() {
                try {
                    pos = Calculo.Calcular();
                    //Manipulate your UI elements as following
                    MainActivity.this.runOnUiThread(new Runnable() {
                        public void run() {
                            mostrarFrases(pos);
                        }
                    });
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
Comments