Context issues trying to display Toast

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

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

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.

+3
source share
2 answers

runOnUIThread:

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

, doInBackground , .

+2

MyObject.this 

AsyncTask

0

Source: https://habr.com/ru/post/1764569/


All Articles