问题
I'm using an AsyncTask
class to add, remove and clear items from my ArrayAdapter
. Unfortunately, when any of those tasks are run, the ArrayAdapter
wants to notifyDataSetChanged()
, which requires that the thread be run on the uiThread
.
If I use runOnUiThread(new Runnable(){...});
in order to update an ArrayAdapter Asynchronously, doesn't that defeat the purpose of trying to update it in a new Thread to begin with?
What is the best approach here?
回答1:
Do .notifyDataSetChanged()
insde onPostExecute()
method. onPostExecute()
method runs on Ui-Thread. If your app requires to periodically update during execution of doInBackground()
method then use publishProgress()
(which will envoke onProgressUpdate()
method) and call notifyDataSetChanged()
inside onProgressUpdate()
method, which also runs on Ui-thread.
回答2:
Just to add something to what everyone else already said, after your task is done running, you might want to set the adapter (or a new one) again for the view you are working with.
AFAIK depending on your code, after notifyDataSetChanged or after refreshing the cursor, the view might not update right away if you are not working with a reference.
If you leave your activity and when you come back, the view is updated, you probably need to set the adapter again.
回答3:
To answer your first question, calling runOnUiThread doesn't defeat the purpose as long as the only thing you call on the UI thread is notifyDataSetChanged()
. Do all your actual, potential long running, tasks in the AsycnAdpater and then when you're ready to tell the activity things have changed, call runOnUiThread()
. It will only run the commands you specify in the Runnable you pass to it.
That said, why not instead of using an AsyncTask, try using an AsyncTaskLoader. AsycnTaskLoaders were designed almost specifically for populating lists asynchronously. They weren't introduced until API level 10, but you can still access them from older API levels by using the android Support Package.
来源:https://stackoverflow.com/questions/7882475/android-how-to-update-arrayadapter-asynchronously