开发者

Problems with context when trying to display Toast

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() inste开发者_JAVA技巧ad of cxt, but with the same result.


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.


You have to use

MyObject.this 

inside of the AsyncTask

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜