Maneesh
Maneesh

Reputation: 6128

application crashes while putting setContentView in thread class in emulator

when I put the setContentView in thread as below, it crashes while running in emulator.

      new Thread(){
          public void run() {           
               setContentView(R.layout.main_layout);
          }  
      }.start();

Upvotes: 0

Views: 2591

Answers (3)

rDroid
rDroid

Reputation: 4945

Contents that should be displayed on the screen can only be called in the UI thread. The other threads have no access to UI elements. If you want to display something on the screen once your background thread is completed or notify something from the background thread you can use handler:

new Thread(new Runnable(){
public void run(){
//to do task in thread
Message msg=new Message();
msg.what=10;//specify some message content to check from which thread u r receiving the //message
handler.sendMessage(msg);
}
}).start();

and in handler:

Handler handler=new Handler(){
void handleMessage(Message msg){
if(msg.what==10){
//carry out any UI associaed task that you want
}
}
};

This method will ensure any thread that should run in background does not interfere wih UI thread, UI does not get slow, and you can update UI/ show dialogs by this method.

runInUIThread() method will put the thread in UI and the UI may become slow if your thread is downloading data form network or writing/reading from/to disk.

Hope this helps.

Upvotes: 0

Jim Blackler
Jim Blackler

Reputation: 23169

You could try...

runOnUiThread(new Runnable(){

  public void run() {
    setContentView(R.layout.main_layout);

  }});

.. but be careful as the convention is to do setContentView(..); in onCreate() on the default thread there.

Upvotes: 2

Samuh
Samuh

Reputation: 36484

that is because setContentView cannot be called from a non-UI thread.

Upvotes: 3

Related Questions