Reputation: 1112
I have a button, when user clicks it, it will update the entire UI(textview, graphs). The content of the UI comes from a SQLite database, I named the update function loading(). You could imagine, inside the loading(), there are lots of database operations and UI updates. When the size of the data getting bigger, the time for this loading() to be done is longer, so the button will stay in pressed state for a longer time.
I tried to use asynctask to deal with this situation so that a progressdialog comes out instead of the button freezed, but I cannot place the loading() method on the doinbackground() of asynctask because doinbackground() cannot touch the UI components that are declared from the onCreate() method of its activity.
I don't want to rewrite the loading() function.
Any other way to do so?? Please help, and if you could, please provide some examples, I appreciate that.
Upvotes: 1
Views: 199
Reputation: 83527
I'm learning about Handler
s currently and according to the documentation, they are the currently recommended way to access data because, for one thing, they do asynchronous loading for you. As you said, you can't access the UI components from another thread other than the UI thread. This means that whether you use a Handler
or roll your own code with AsyncTask
that you need to separate the code that updates the UI from the code that loads the data.
Upvotes: -2
Reputation: 59178
If you run time-taking tasks on main application thread (a.k.a., UI thread) you will have unresponsive UI and eventually see the famous Application Not Responding (ANR) dialog.
Recommended way is to do these in AsyncTask and call publishProgress()
in doInBackground()
. Put your UI-updating logic in onProgressUpdate()
of your AsyncTask
. onProgressUpdate()
will be automatically called on the main application thread after you call publishProgress()
.
Upvotes: 3
Reputation: 28541
Best option would in my opinion to use an AsyncTask to do this job. You can trigger progress update from loadInBackground to get some UI update when you need (call publishProgress()
from the task background thread and the method onProgressUpdate()
will get called on the UI thread).
Other option: have the job done in a separate thread or in a background service. Then from your UI, you can trigger a refresh every X milliseconds using a Handler.
Upvotes: 1
Reputation: 7814
In order to use AsyncTask in this instance you want to load the data in doInBackGround() and populate some kind of datastructure or model object with the results. Then return that as the result of doInBackground().
onPostExecute() does run on the UI thread and can use the result to populate and update your components.
Upvotes: 1
Reputation: 31283
You can run things on the UI thread using runOnUiThread(Runnable)
. You could also use a combination of Thread
and Handler
.
Upvotes: -1