bahtiyartan
bahtiyartan

Reputation: 1030

Background Thread fails while setting EditText's value

I have a thread that call's MainActivies method that sets text value of EditText but it fails.

MyRunnable is like that:

public class MyRunnable implements Runnable {

    MainActivity mController;

    public SoundTrigger(MainActivity pController) {
        mController = pController;
    }

    @Override
    public void run() {     
        for (int i = 0; i < 10000; i++) {

            if(i % 100) {
                mController.triggered(i);
            }

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

In MainActivity class my triggered method like this:

public void triggered(int nNum) {

    EditTextInstance.setText(nNum+"");

}

but it fails. All i need is printing a real time data that is created by a background thread on an edittext component.

Upvotes: 1

Views: 94

Answers (1)

Al&#233;cio Carvalho
Al&#233;cio Carvalho

Reputation: 13647

make it like this:

 @Override
 public void run() {     

     for (int i = 0; i < 10000; i++) {
          if(i % 100) {
           mController.runOnUiThread(new Runnable() {
                 public void run() {
                    mController.triggered(i);
                 }
           });

    }

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

Explanation: you were previously changing an UI element from a Non-UI thread and this is not good. This code should work, BUT it is still not the recommended way to approach the problem. You should use something like a AsyncTask where you have a template method for 'background' operation (non-ui thread operation) and the 'onPostExecute' which already executes on the UI thread.

another additional note: NEVER call Thread.sleep(); on the UI Thread (a.k.a. Main thread)

Upvotes: 2

Related Questions