Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android UI: when can I directly modify a view?

I have an app with two activities. From the main activity I start a secondary activity using startActivityForResult(). The secondary activity returns data (in the form of an Intent object) to the main activity. On the main activity I have a method onActivityResult() to handle the come back from the secondary activity.

Within this onActivityResult() method, I need to update a View on the main activity (to reflect the new data values). I do not explicitly spawn any threads. My question is: can I directly modify the view from within onActivityResult() method, or do I need to put an event on the UI queue to do it? To be more explicit: can I be sure that the onActivityResult() method is on the UI thread, and in that case can I forget about the UI queue?

like image 317
Luis Mendo Avatar asked Jul 21 '13 16:07

Luis Mendo


People also ask

Can we update UI from service?

This example demonstrate about How to update ui from Intent Service. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.

Can we update UI from background thread?

In this case, to update the UI from a background thread, you can create a handler attached to the UI thread, and then post an action as a Runnable : Handler handler = new Handler(Looper. getMainLooper()); handler. post(new Runnable() { @Override public void run() { // update the ui from here } });


3 Answers

Although onActivityResult is on Ui thread, you may not see your UI updated when modified in onActivityResult. I suspect the reason is redrawing of Ui elements at onResume which forces ui elements to reset by calling resetViews() of ActivityTransitionState at super.onResume().

I faced with this issue while simply updating an EditText inside onActivityResult. EditText was not updated.

The workaround is to save your data in onActivityResult and update Ui at onResume by setting a flag in onActivityResult.

like image 76
Buddy Avatar answered Oct 09 '22 23:10

Buddy


  1. Yes, you can modify the view in onActivityResult(). You can modify an Activity's views anytime after you call setContentView() in onCreate(), as long as you are running on the UI thread.

  2. Yes, onActivityResult() is called on the UI thread. This is true for all life cycle methods (onCreate(), onResume(), etc).

like image 24
Jeffrey Blattman Avatar answered Oct 09 '22 22:10

Jeffrey Blattman


The onActivityResult() is executed in the UI thread, you can modify the view on this method.

like image 43
David SN Avatar answered Oct 09 '22 22:10

David SN