I am trying to display Toast inside AsyncTask. This first piece of code is put into an action that we can name MyActivity, and works just fine:
Toast.makeText(this, "Toast!", Toast.LENGTH_SHORT).show();
Then I create a new instance MyObjectand call method(). This code also fits in MyActivity.
MyObject obj = new MyObject(this);
obj.method();
This is the definition MyObject. ProgressDialog works great, but no toasts.
public class MyObject {
Context cxt;
public MyObject(Context cxt) {
this.cxt = cxt;
}
public void method() {
new MyAsyncTask().execute();
}
private class MyAsyncTask extends AsyncTask<Object, Integer, Boolean> {
protected void onPreExecute() {
Toast.makeText(cxt, "Toast!", Toast.LENGTH_SHORT).show();
}
protected Boolean doInBackground(Object... params) {
Looper.prepare();
Toast.makeText(cxt, "Toast!", Toast.LENGTH_SHORT).show();
}
}
}
I thought I was doing the same thing in my first example and below, but apparently I was missing something. I also tried it getApplicationContext()and cxt.getApplicationContext()instead cxt, but with the same result.
nip3o source
share