Android: AsyncTask, UI Threading made easy
AsynkTask is a class that allows for easy use of UI Threading. AsyncTask allows you to preform background tasks in a separate thread with out disrupting the UI thread. In ShotShakr 2.0 I am using AsyncTask to filter the list of shots when a filter is selected. In order to use AsyncTask it must be subclassed and override at least one method (doInBackground(Params… )).
Here is ShotShakr’s UpdateShot Class. Here i am passing in the list of filters and shots.
private class UpdateShots extends AsyncTask<String, Void, ArrayList<Shot>> {
private ArrayList<String> aFilters;
private ArrayList<Shot> aShots;
public UpdateShots(ArrayList<String> filters, ArrayList<Shot> allShots){
aFilters = filters;
aShots = allShots;
}
}
doinbackground method does the work of the filtering and after completion postExecute gets fired. Here is where i update the UI Thread with the results.
@Override
protected void onPostExecute(ArrayList<Shot> result) {
//Update UI Thread
shotpicker.this.filteredShots = result;
}
@Override
protected ArrayList<Shot> doInBackground(String... params) {
ArrayList<Shot> newShots = new ArrayList<Shot>();
//filter shots
// add to new list
//sends to postexecute
return newShots;
}
Here is how to fire of the AsyncTask
new UpdateShots(filters,allShots).execute();
See a more detailed how to http://developer.android.com/reference/android/os/AsyncTask.html
Cheers
