Android Novice Android Novice - 10 months ago 61
Android Question

Android AsyncTask

Am i fully utilising my AsyncTask? Can someone correct my codes if it is wrong. I just want to make sure my AsyncTask fully works so i wont get any trouble in the future. I wish to use AsyncTask for all my classes. Is it a good practice?

public class SingleMenuItemActivity extends Activity {

// XML node keys
static final String KEY_TITLE = "title";
static final String KEY_ARTIST = "artist";
static final String KEY_THUMB_URL = "thumb_url";
private ProgressDialog pDialog;
String title;
String artist;
String image_url;
ImageView view;

public void onCreate(Bundle savedInstanceState) {
new loadSingleView().execute();

view = (ImageView) findViewById(;

public class loadSingleView extends AsyncTask<String, String, String> {

protected void onPreExecute() {
pDialog = new ProgressDialog(
pDialog.setMessage("Connecting to Server ...");
protected String doInBackground(String... args) {
// updating UI from Background Thread

Intent in = getIntent();

image_url = in.getStringExtra(KEY_THUMB_URL);
title = in.getStringExtra(KEY_TITLE);
artist = in.getStringExtra(KEY_ARTIST);

return null;

protected void onPostExecute(String args) {
// dismiss the dialog after getting all products

ImageLoader imgLoader = new ImageLoader(getApplicationContext());

imgLoader.DisplayImage(image_url, view);

TextView lblName = (TextView) findViewById(;
TextView lblCost = (TextView) findViewById(;


Answer Source

You have to update the UI from the method onPostExecute(). I like to move my task into their own files. This way we have a separation of concerns which makes it more easier to understand the code. We can do this by using a interface to define a callback method

public class LoadSingleView extends AsyncTask<String, String, String> {

    public interface LoadSingleViewHandler {
        void onSingleViewLoad(String result);

    private LoadSingleViewHandler handler;

    public LoadSingleView(LoadSingleViewHandler handler) {
        this.handler = handler;

    protected String doInBackground(String... args) {
        // Do operation here and return the result
        // Operation is usually some network request
        // or something that will take alot of time

    protected void onPostExecute(String result) {

Now just start the task from the activity and have the activity implement LoadSingleViewHandler interface.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download