I assume that we cannot update the UI view elements ( TextView , EditText , etc.) in any workflow, but in the example below, I can update the views from the workflow, not always, but only sometimes.
Below is an example where I am updating user interface elements in a workflow -
public class AndroidBasicThreadActivity extends AppCompatActivity { public static TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_android_basic_thread); textView = (TextView) findViewById(R.id.textview); MyAndriodThread myTask = new MyAndriodThread(); Thread t1 = new Thread(myTask, "Bajrang Hudda"); t1.start(); } }
Here is my workflow -
class MyAndriodThread implements Runnable { @Override public void run() { AndroidBasicThreadActivity.textView.setText("Hello!! Android Team :-) From child thread."); } }
Believe me, I will not get any exception saying:
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
And I can see the UI updates on the emulator.
But if I am doing a heavy task (sleeping) in a workflow, then I got the exception expected above, why is this happening? I'm a new guy on a multi-threaded android, please get me out of this confusion.
If I change my workflow to this, I will get the above exception -
class MyAndriodThread implements Runnable { @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } AndroidBasicThreadActivity.textView.setText("Hello!! Android Team :-) From child thread."); System.out.println("Child thread completed."); } }
And if my user interface or main thread is waiting (join ()), then I get the exact output without exception at all, see this -
MyAndriodThread myTask = new MyAndriodThread(); Thread t1 = new Thread(myTask, "Anhad"); t1.start(); try { t1.join(); } catch (InterruptedException e) { e.printStackTrace(); }
Update
At first I thought it was a rendering scheme, and then I changed my program using the ProgressBar. Then I got a really unexpected result ... However, an exception means that I can update my progress bar in the workflow. See below -
@Override public void run() { for(int i = 1; i<=10; i++) { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } activity.progressBar.setProgress(i); } }