Is there a way to do UI changes in a non-UI thread? Short question.
6 Answers
Either use Handler or use below code
runOnUiThread(new Runnable()
{
@Override
public void run()
{
// Ui Stuff here
}
});

- 15,249
- 7
- 52
- 81
There are many way to do this, use AsyncTask or Threads. Short answer.
Hint: the UI stuff can be done in the pre-postExecute/runOnUiThread/Handler class

- 33,594
- 11
- 89
- 102
If you dont want to use an AsyncTask, try the observer pattern with an inner class (ResponseHandler) in your main activity, sorry I couldnt get the formatting right but im sure you get the idea
public class WorkerThread extends Observable implements Runnable {
public void run() {
try {
DoSomething();
String response = "Doing something";
setChanged();
notifyObservers( response );
DoSomethingElse();
String response = "Doing something else";
setChanged();
notifyObservers( response );
}
catch (IOException e) {
e.printStackTrace();
}
}
private void DoSomething(){
}
private void DoSomethingElse(){
}
public class MainActivity{
public class ResponseHandler implements Observer {
private String resp;
public void update (Observable obj, Object arg) {
if (arg instanceof String) {
resp = (String) arg;
//Write message to UI here ie System.out.println("\nReceived Response: "+ resp );
//or EditText et = (EditText)findViewById(R.id.blah);
// blah.SetText(resp);
}
}
}
private void doStuffAndReportToUI(){
final WorkerThread wt = new WorkerThread();
final ResponseHandler respHandler = new ResponseHandler();
wt.addObserver( respHandler );
Thread thread = new Thread(wt);
thread.start();
}

- 1,508
- 14
- 13
Check out the Handler class. Or take a look at these similar questions:

- 1
- 1

- 42,483
- 9
- 127
- 120
-
well the basic problem is that, that thread is in other class than my main activity, and it is doing something in a infinite loop (sockets etc). – Knobik Jun 05 '11 at 05:27
I tried +tmho answer, but it still gives this error:
E/AndroidRuntime(****): android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
I finally end up combinning it with +ingsaurabh way, like that:
private class ResponseHandler implements Observer, Runnable {
Activity act;
public ResponseHandler(Activity caller) {
act = caller;
}
@Override
public void update (Observable obj, Object arg) {
act.runOnUiThread(this);
}
@Override
public void run() {
//update UI here
}
}
thanks both of you.

- 5,756
- 3
- 39
- 36
Try to explore runOnUIThread()
http://developer.android.com/reference/android/app/Activity.html#runOnUiThread(java.lang.Runnable)

- 1,620
- 1
- 16
- 33