Reputation: 352
I have to update a TextView
from another class (not a activity) with the result from a method which can be slow to finish its search. While the method don't finish I thought set the TextView
text to something like "loading..." and finally, after method result is ok, set the text to that result. Currently I'm doing something like this:
textView.setText("loading...");
Search s = searcher.search();
textView.setText(s.result);
Firstly, this still freezes the application until result is ok, once didn't not used new Threads
. I know that to set content to Android widgets we have to do it inside the uiThread
, but I don't know how to do it in my case, once I'm not inside a Activity
.
In second place, that approach are not showing the "loading..." text. When I call that code the application just freezes and back with the final text.
Then, how to avoid that freeze/breaking until content is ok?
Upvotes: 0
Views: 2892
Reputation: 543
I think the main thing to understand is that only UI specific tasks should run on the UI thread. If it is not UI related then it should run on another thread ideally as an AsyncTask.
Performing a search, generally speaking, is very performance heavy as you have pointed out. This will block the UI thread from updating the UI which will lead to unresponsive UIs and users may perceive this a crash or a slow app.
So firstly, to run the updating on the UI Thread.
runOnUiThread(() ->{textView.setText("loading...");});
then perform the search on a different thread
then once the search is finished update the UI using the same method as above
Upvotes: 0
Reputation: 1310
Do not do heavy operation inside MainThread (UI) in Android. For your case take a look to AsyncTask. It give you a method doInBackground
where you should make some background stuff (http request, file i/o) then you will get call onPostExecute
, that method will called on UI Thread with the results of doInBackground
method. Another example.
Upvotes: 1