Ofek Ron
Ofek Ron

Reputation: 8580

Having a TextView show text set by another Thread android

I have some worker thread that gets an address using the geocoder, and when its done, i want to show the result on the application thread's TextView, using setText() from the worker thread leads to an exception, so what is the best practice to do that?

Upvotes: 0

Views: 768

Answers (3)

yrajabi
yrajabi

Reputation: 647

Try this inside your thread where you want to set text:

    // you should finalize your text before using it in another thread, 
    // else the IDE would show an error
    final String text = yourTextToBeSet;
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            textView.setText(text);
        }
    });

The exception you get when you call setText() on non-UI thread is because you can't call anything related to UI when you are on a non-UI thread. You can, as above, easily call runOnUiThread(Runnable) to divert code execution on UI thread.

Keep in mind that this solution is not good enough if your code is not as simple as that, which in such situations, using AsyncTask is recommended.

Upvotes: 1

Ben
Ben

Reputation: 761

It's hard to say without seeing your code or knowing what exception:

but check if:

  • your textView object is linked with the one in your layout (findViewById(R.id.textView1))
  • is it visible in you layout?(sometimes when dimensions of elements dont't add up, views get pushed off screen)
  • Is it really a String you're trying to set? (not an int or so?)

Upvotes: 1

s.d
s.d

Reputation: 29436

Android UI Views must not be touched from external threads, Any code that calls Methods on Views must run in UI thread only. You Should use AsyncTask . It provides useful callback methods to update UI from task running in a separate thread.

Upvotes: 1

Related Questions