Question

I want to display a Toast in my background thread in the doInBackground method. Of course, this doesn't work. So I tried this

int error = 1;
publishProgress(error);
Log.i ( "InternetConnection" , "Loading Internet from Cache not working because of no Internet connection." );
return null;

And the onProgressUpdate method is

protected void onProgressUpdate ( Integer integers ){
    if ( integers == 1){
        Toast.makeText ( c.getApplicationContext(), "Daten konnten nicht geladen werden.", 0).show();
    }
}

Isn't it right, that when I call publishProgress the onProgressUpdate is used?

C is by the way my activity, so

Context c = MainActivity();

How can I possibly show a Toast, because with this code it's not showing up.

Was it helpful?

Solution

Display Toast in doInBackground when I have exception

onProgressUpdate() method takes array of T objects (generally), in your case array of Integers.

You need to correct your method! Now it's not override super class method. Ten you are passing into this method number 1 so you need to correct your method.

The method have to looks like this:

protected void onProgressUpdate(Integer... integers) {
    int value = integers[0];
   if (value == 1) {
      // show your Toast    
   }
}

And now it should works.

Please have a look carefully at AsyncTask docs.

OTHER TIPS

Put the log in doInBackground itself but use Handlers to do so.

handler.post(new Runnable() {

                            @Override
                            public void run() {
                                // TODO Auto-generated method stub
                               //your logs here.
                            }
                        });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top