views:

52

answers:

2

I try to display a Toast inside a AsyncTask. This first piece of code is placed in an activity that we may call MyActivity, and works fine:

Toast.makeText(this, "Toast!", Toast.LENGTH_SHORT).show();

Then I create a new instance of MyObject and calls method(). This code is also placed in MyActivity.

MyObject obj = new MyObject(this);
obj.method();

This is the definition of MyObject. The ProgressDialog works fine, but no toast is showed.

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(); // works fine
    }

        protected Boolean doInBackground(Object... params) {
           Looper.prepare();
           Toast.makeText(cxt, "Toast!", Toast.LENGTH_SHORT).show(); // doesn't work
        }
   }
}

I believed I was doing exactly the same thing in my first example and below, but appearently, I'm missing something. I've also tried getApplicationContext() and cxt.getApplicationContext() instead of cxt, but with the same result.

+2  A: 

Wrap that into the runOnUIThread method:

runOnUiThread(new Runnable() {
    public void run() {
        Toast.makeText(cxt, "Toast!", Toast.LENGTH_SHORT).show();
    }
});

That's because the doInBackground method is not executed on the UI Thread, so you have to force that.

Cristian
A: 

You have to use

MyObject.this 

inside of the AsyncTask

schwiz