0

I am writing a server client on android platform. If one of the client send a message one of them, firstly message goes to server and server sends it to client. When a receiver client receive the message, i have to setContentView so I need to open messaging screen. But it takes the messages in a different thread and I pass as a reference my activity class.

Thread my = new MyThread(this);

and in the thread class ı cant set content view because give an error like ViewRoot CalledFromWrongThread what can I do?

Caner
  • 57,267
  • 35
  • 174
  • 180
Emre
  • 13
  • 4

3 Answers3

7

The UIThread is the main thread of execution for your application. This is where most of your application code is run. All of your application components(Activities, Services, ContentProviders, BroadcastReceivers) are created in this thread, and any system calls to those applications are performed in this thread.

When you explicitly spawn a new thread to do work in the background, this code is not is not run on the UIThread. So what happens if the this background thread needs to do something that changes the UI? This is what the runOnUiThread is for. Actually you're supposed to use a Handler (see the link below for more info on this); it provides these background threads the ability to execute code that can modify the UI. They do this by putting the UI-modifying code in a Runnable object and passing it to the RunOnUiThread method.

(See https://stackoverflow.com/a/3653478/448625 for a more detailed explanation of what UI thread is)

In short, this should fix it:

runOnUiThread(new Runnable() {
    public void run() {
        // some code that needs to be ran in UI thread
    }
});
Community
  • 1
  • 1
Caner
  • 57,267
  • 35
  • 174
  • 180
  • Thanks for your help. Thread threadReciever = new ThreadRecieve(this); threadReciever.start(); this is my thread nad when ı got the message ı try to change contentview. So you advice me to use a runOnUiThread wright? – Emre Jul 20 '12 at 13:09
  • I recommend you to put `setContentView` line inside `run()` method in my answer – Caner Jul 20 '12 at 13:13
2
ActivityName.this.runOnUiThread(new Runnable() {
     @Override
     public void run() {
         // set contentview here
     }
});
Carnal
  • 21,744
  • 6
  • 60
  • 75
  • But my thread is a different class and does a lot of things not just the set content. Thread threadReciever = new ThreadRecieve(this); threadReciever.start(); i create it this way. so what do you suggest? – Emre Jul 20 '12 at 13:11
0
ActivityName.this.runOnUiThread(new Runnable() {
     @Override
     public void run() {

     }
});
XEME
  • 43
  • 1
  • 7