-1

I know if I want to use a thread in UI group, must use a handler. because, android UI is single thread model. so, If another thread accesses the UI, occur

android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

so I use handler but same occur error message.

private static TextView sTextView; //global variable
public void showText(final TextView textView) {
   sTextView = textView;
   sTextView.findViewById(R.id.text);
   Looper.prepare();

   final Handler handler = new Handler();
   new Thread(new Runnable() {
      @Override
        public void run() {
                handler.post(new Runnable() {
                    @Override
                    public void run() {
                       sTextView.setText("123123123");
                    }
                });
        }
      }).start();
      Looper.loop();
    }

    and showText called    

private VideoCapture videoCapture; //global variable
private TextView mText;  //global variable

public void beginCapture() {
   videoCapture.showText(mText);
}

  and I build. but occur error.  

Pushpendra
  • 2,791
  • 4
  • 26
  • 49
chohyunwook
  • 203
  • 2
  • 3
  • 14
  • Possible duplicate of [Android "Only the original thread that created a view hierarchy can touch its views."](http://stackoverflow.com/questions/5161951/android-only-the-original-thread-that-created-a-view-hierarchy-can-touch-its-vi) – Mohammed Atif Mar 22 '17 at 09:22

1 Answers1

0

It should be the UI thread, not any random thread.

For fragment:

((Activity)mContext).runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sTextView.setText("123123123");
            }
        });

For Activity:

MyActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                sTextView.setText("123123123");
            }
        });

Thats it, you don't need any Handlers or Loopers or Threads just the above lines of code.

Mohammed Atif
  • 4,383
  • 7
  • 28
  • 57