Search code examples
javaandroidtoast

How can I show a Toast from AsyncTask onPostExecute?


When my AsyncTask finishes, I display info in a TextView.

    @Override protected void onPostExecute(Void x)
    {
      MainActivity.lblLastLetterProcessed.setText("A-Z loaded");
    }

Like so:

  public static void setLastLetterProcessed(char c){
    lblLastLetterProcessed.setText("" + c);
  }

I'd rather give the info via Toast but Toast requires Context.

protected void onPostUpdate(Integer... progress) 
{
  Toast toast= Toast.makeText(???????????, "Loaded A-Z", Toast.LENGTH_LONG);
  toast.show();
}

So I wrote popupMessage:

  void popupMessage(String text)
  {
    SpannableStringBuilder altText = new SpannableStringBuilder(text);
    altText.setSpan(new ForegroundColorSpan(0xFFCC5500), 0, altText.length(), 0);
    int duration = Toast.LENGTH_SHORT;
    Context context = getApplicationContext();
    Toast toast = Toast.makeText(context, altText, duration);
    toast.setGravity(Gravity.TOP | Gravity.CENTER, 0, 0);
    toast.show();
  }

But I can't call it from onPostUpdate since popupMessage is NOT static.

If I make it static, I can't use getApplicationContext. And if I add Context as a parameter, I can't pass Context from onPostUpdate.

Googling has provided no SO Answers I can implement.

What can I do?


Solution

  • public class MyTask extends AsyncTask<Void, Void, Void>{
        private Context mContext;
    
        public MyTask(Context context){
            mContext = context;
        }
    
        ...
        ... 
    
        protected void onPostUpdate(Integer... progress){
            Toast toast= Toast.makeText(mContext, "Loaded A-Z", Toast.LENGTH_LONG);
            toast.show();
        }
    }
    

    and instantiate it like so:

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

    This is how I do AsyncTask's that require arguments, I also define callbacks this way in the constructor of the Tasks to interact with the activities that call them.