0

I have added a TextView to a RelativeLayout that I already added a SurfaceView to. I can get the TextView to display text over my SurfaceView.

rl = new RelativeLayout(this);
tv = new TextView(this);
tv.setText(Integer.toString(GameScreen.score));
tv.setTextSize(50);
tv.setPadding(390, 50, 0, 0);
tv.setTextColor(Color.BLACK);
rl.addView(renderView);
rl.addView(tv);
setContentView(rl);

Then in my GameScreen class's update method i put:

game.getTextView().setText(Integer.toString(score));

And it gives me the error:

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

What can I do to get around this ?

Noitidart
  • 32,739
  • 29
  • 126
  • 286
  • 2
    Possible duplicate of [Android - ViewRootImpl$CalledFromWrongThreadException](http://stackoverflow.com/questions/10118301/android-viewrootimplcalledfromwrongthreadexception) – rkosegi Mar 01 '16 at 06:22
  • Thanks rkosegi I read it, but the solution from ankit made some sense, but I didn't understand it till @MustansarSaeed explained it – Noitidart Mar 01 '16 at 06:33
  • Possible duplicate of [Android update TextView in Thread and Runnable](http://stackoverflow.com/questions/12716850/android-update-textview-in-thread-and-runnable) – OnePunchMan Mar 01 '16 at 10:34

3 Answers3

3

Use the following which is the recommended way to update Widget on UiThread

game.getTextView().post(new Runnable() {
                @Override
                public void run() {
                    game.getTextView().setText(Integer.toString(score));
                }
            });

Hope this helps.

Mustansar Saeed
  • 2,664
  • 2
  • 19
  • 43
1

run your code in the UI thread. You cannot do UI operations from a worker thread.

your_context.runOnUiThread(new Runnable() {
    public void run(){   
        game.getTextView().setText(Integer.toString(score));
    }
});
Ankit Aggarwal
  • 5,167
  • 2
  • 28
  • 50
  • Thanks for the fast reply, this solution is correct, but didn't make sense to me till I saw @Must solution below. But definitely up vote, thank you very much! – Noitidart Mar 01 '16 at 06:34
1

Use this peice of code.. Um sure it will help you out !

private void runThread() {

    new Thread() {
        public void run() {

                try {
                    runOnUiThread(new Runnable() {

                        @Override
                        public void run() {
                           game.getTextView().setText(Integer.toString(score));
                        }
                    });

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

        }
    }.start();

Let me know if it works! :)

Vivek Bhardwaj
  • 511
  • 5
  • 15