getting context in AsyncTask

D4rWiNS picture D4rWiNS · Jun 4, 2013 · Viewed 71.7k times · Source

I am trying to get the context in my AsyncTask of the class called Opciones(this class is the only one that call that task) but I don't know how to do it, I saw some code like this:

      protected void onPostExecute(Long result) {

    Toast.makeText(Opciones.this,"Subiendo la foto. ¡Tras ser moderada empezara a ser votada!: ", Toast.LENGTH_LONG).show(); 
}

But it doesn't work for me it says: "No enclosing instance of the type Opciones in scope"

Answer

Chintan Rathod picture Chintan Rathod · Jun 4, 2013

You need to do following things.

  • when you want to use AsyncTask, extend that in other class say MyCustomTask.
  • in constructor of new class, pass Context

Example

public class MyCustomTask extends AsyncTask<Void, Void, Long> {

    private Context mContext;

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

    //other methods like onPreExecute etc.
    protected void onPostExecute(Long result) {
         Toast.makeText(mContext,"Subiendo la foto. ¡Tras ser moderada empezara a ser votada!: ", Toast.LENGTH_LONG).show(); 
    }
}

And instantiate class by following.

MyCustomTask task = new MyCustomTask(context);
task.execute(..);