0

Error: Getting error with UI thread.. when I'm trying to show an alert inside the doInBackground. Is there any posibility do this stuff?

private class LoggingTask extends AsyncTask<String, Void, Integer> {

    @Override
    protected Integer doInBackground(String... params) {
                 //Get the sever connection and return the status

    if(status==0){
             // show an alert here....
    }
        return status;
    }
Girish Nair
  • 5,148
  • 5
  • 40
  • 61
Joyal
  • 414
  • 7
  • 19

6 Answers6

1
@Override
protected Integer doInBackground(String... params) {
    // Get the sever connection and return the status

  publishProgress()
  @Override
  protected void onProgressUpdate(Void... values) {
  // TODO Auto-generated method stub
  super.onProgressUpdate(values);
 //Do what ever you want 
    }
0

Do in background method doesnot allowed for UI changes,if you want to make any UI changes do in onpostexecute method

Gajendran
  • 13
  • 6
0

Do this way

@Override
    protected Integer doInBackground(String... params) {
        // Get the sever connection and return the status

        if (status == 0) {
            new Handler().post(new Runnable() {

                @Override
                public void run() {
                    // show an alert here....

                }
            });

        }
        return status;
    }
Biraj Zalavadia
  • 28,348
  • 10
  • 61
  • 77
  • @biraj.. you right but if using Thread Handler ,the AsyncTask can be thrown out.. – Joyal Nov 21 '13 at 07:05
  • 1
    another solution is onPostExecute() given by @ Coderji – Biraj Zalavadia Nov 21 '13 at 07:07
  • Already I followed tat way.. problem is tat ,if this AsyncTask is in login functionality, status from server is Invalid Login, want to show alert from doInBack and exit the app.. your way is also good..Thank you – Joyal Nov 21 '13 at 07:17
0

Make a method that creates the dialog in your activty ( context would be the activity ) not in the AsyncTask. So when your

if ( status == 0 )

returns true, you call the method from the UI thread. In this way you are not creating the dialog in the AsyncTask and it should work.

Hitman
  • 588
  • 4
  • 10
0

doInBackground() is not the right place to do the UI related Task. You have to do it in onPostExecute. Or you can can start the dialog in OnPreExecute() and than cancel the dialog onPostExecute().

Jatin Malwal
  • 5,133
  • 2
  • 23
  • 26
0

Async tasks don't run on the ui thread that's why you can't do that. Store a boolean. Then call the alert dialog after the asynchronous task completes in the onpostexecute method.

Dave Hulse
  • 70
  • 6