The threads do not work on android

0

I'm doing an app that is increasing the seconds, later I'll add other functions, but for the moment, I mark an error at the moment that the threads start working marks me this error.

  

Only the original thread that created a view of the hierarchy can touch its   views.

And my code is as follows

public class MainActivity extends AppCompatActivity {

TextView tv;
int seg=0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    tv=(TextView)findViewById(R.id.reloj);
}
boolean on=false;
public void inicia(View view){
    if(!on){
        tiempo.start();
        on=true;
    }

}

Thread tiempo=new Thread(){
    public void run(){
        try{
            while(true){
                Thread.sleep(1000);
                seg++;
                tv.setText(seg+"");
            }

        }catch (InterruptedException e){

        }
    }
};
}
    
asked by Montero 08.11.2016 в 05:48
source

2 answers

2

Only the main thread can modify the user interface (UI), so you must use runOnUiThread to modify any view:

You can easily modify your code to do what you want:

Thread tiempo = new Thread() {
  public void run() {
    try {
      while(true) {
        Thread.sleep(1000);
        seg++;
        runOnUiThread(new Runnable() {
          @Override
          public void run(){  
            tv.setText(Integer.toString(seg));
          }
        });
      }
    } catch (InterruptedException e) {
    }
  }
};

Edit to complete the solution with AsyncTask.onProgressUpdate :

As @Sergio Martín Vílchez has suggested, it can also be done with AsyncTask , although I prefer the previous solution:

/* Parámetros de entrada (Void), progreso (Integer) y salida (Void) */
new AsyncTask<Void, Integer, Void>() {
  @Override
  protected Void doInBackground(Void... params) {
    while(true) {
       Thread.sleep(1000);
       publishProgress(seg++);
    }
    return null;
  }

  @Override
  protected void onProgressUpdate(Integer... progreso) {
    /* Esto se ejecuta en el hilo de la interfaz de usuario (UI) */
    tv.setText(Integer.toString(progreso[0]));
    /* También podría haberse usado directamente:
    tv.setText(Integer.toString(seg));*/
  }
}.execute();
    
answered by 08.11.2016 / 08:16
source
0

Try using AsynTask:

link

It will greatly facilitate tasks that need to run in the background.

    
answered by 08.11.2016 в 08:40