Make some Android UI elements in a thread other than UI

Is there a way to make user interface changes in a thread other than the UI? Short question.

+8
java android multithreading user-interface
source share
6 answers

If you do not want to use AsyncTask, try the observer pattern with the inner class (ResponseHandler) in your main action, sorry, I could not get the formatting correctly, but I'm sure you will 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(); } 
+5
source share

Use Handler or use below code

  runOnUiThread(new Runnable() { @Override public void run() { // Ui Stuff here } }); 
+9
source share

There are many ways to do this, use AsyncTask or Threads . The short answer.

Hint: UI stuff can be done in the pre-postExecute / runOnUiThread / Handler class

+5
source share

Check out the Handler class. Or take a look at these similar questions:

Update user interface from stream

Processing UI code from a stream

updating ui from stream using audiotrack

+1
source share
0
source share

I tried + tmho to answer, but it still gives this error:

E / AndroidRuntime (****): android.view.ViewRootImpl $ CalledFromWrongThreadException: only the source thread that created the view hierarchy can touch its views.

I finally end the combination with the + ingsaurabh method, for example:

 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 to both of you.

0
source share

All Articles