Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Raising a Toast From AsyncTask

I'm trying to raise a toast from asynctask, but I'm having trouble getting my parameters right. I'm toasting from onProgressUpdate, so I'm on the UI thread, which I think is correct. I think I'm going wrong with the context parameter, what should I pass in as a value?

EDIT: Showing code below

    @Override
protected void onProgressUpdate(String... strings){
    Toast toast = Toast.makeText(MainActivity.this, strings[0], Toast.LENGTH_LONG);
    toast.show();
}

MainActivity.this is saying "No enclosing instance of the type MainActivity is accessible in scope." I'm not sure what to pass as a context instead.

Thanks

like image 275
Colin Avatar asked Mar 22 '11 01:03

Colin


2 Answers

Get the Context object by calling getApplicationContext() from MainActivity and pass it as a parameter to your AsyncTask. As EboMike has pointed out, MainActivity.this would only work if your AsyncTask was an inner class.

like image 109
dbyrne Avatar answered Nov 05 '22 05:11

dbyrne


If it's not an inner class declared at the point of use then MainActivity.this is likely to be out of scope. The only way to remedy the problem is to subclass AsyncTask and change the constructor to accept a context variable so you can set it in your custom class and use it from methods. Using getApplicationContext might work as well but I'm not sure how it will behave.

like image 2
David K. Avatar answered Nov 05 '22 04:11

David K.