dotty
dotty

Reputation: 41473

How do I pass a context to an AsyncTask?

I want to preform a Toast when a background task is completed, just to let the user know that it's finished.

I've made a new class for my asyncTask, but I cannot use getApplicationContext() within this class.

I'm using task.execute(getTempFile(this), getApplicationContext()); to run the tasks. getTempFile returns a File object, and I was trying to pass the context as a Context object.

My Task class has three variables, AsyncTask<Object, Integer, Integer>, so the context is in the second object. However, this crashes the application.

public class LocationActivity extends Activity implements LocationListener {
    protected void handleImage(Bitmap thumbnail) {
        PushDataToServer task = new PushDataToServer();
        task.execute(getTempFile(this), getApplicationContext());
    }
}


public class PushDataToServer extends AsyncTask<Object, Integer, Integer> {

    Context context;

    @Override
    protected Integer doInBackground(Object... params) {
        // TODO Auto-generated method stub
        this.context = (Context) params[1];
        File file = (File) params[0];
        return null;
    }

    protected void onPostExecute(String result) {
         Toast toast = Toast.makeText(this.context, "All done!", Toast.LENGTH_SHORT);
         toast.show();
    }

}

Upvotes: 22

Views: 24640

Answers (4)

Fernando JS
Fernando JS

Reputation: 4317

Complete example: Reusable AsyncTask

Upvotes: 1

Wroclai
Wroclai

Reputation: 26925

Pass a Context object into the AsyncTask's constructor.

Sample code:

public class MyTask extends AsyncTask<?, ? ,?> {
    private Context mContext;

    public MyTask(Context context) {
        mContext = context;
    } 
}

and then, when you are constructing your AsyncTask:

MyTask task = new MyTask(this);
task.execute(...);

Upvotes: 78

Nikolay Elenkov
Nikolay Elenkov

Reputation: 52956

Pass it in the constructor, not as a method parameter. Then you don't need to depend on the generic parameters.

Upvotes: 2

Jack
Jack

Reputation: 9252

You say your context is in the second object, yet your second object is Integer. Could this be your problem? Also - another suggestion is to put your AsyncTask class as a private inner class to your activity - that way I am pretty sure you will have access to getApplicationContext().

Upvotes: 0

Related Questions