0

I have a fully functional asynctask in my android app, but when I'm not connected it causes my app to crash in the Error message within my Activity (in AlertDialog.Builder) stemming from the Async not connecting. I pass Context to my async, so that may have something to do with it, but not sure.

Below is the code from Async class and Activity. LogCat is telling me error is occurring in the AlertDialog alert builder.create(). How can I solve?

From Async class:

    InputsRecapUploadTask extends AsyncTask<String, Void, Integer> {

public InputsRecapUploadTask(InputsRecap activity,
        ProgressDialog progressDialog, Context ctx) {
    this.activity = activity;
    this.myCtx = ctx;
    this.progressDialog = progressDialog;   
}

@Override
protected void onPreExecute() {
    progressDialog.show();
}

}       
@Override
protected Integer doInBackground(String... arg0) {
    //// http code
                responseCode = 1;
            }
        }
    } catch (Exception e) {
        e.printStackTrace();
        progressDialog.dismiss();
        activity.showLoginError("");
    }

    return responseCode;

}

@Override
protected void onPostExecute(Integer headerCode) {
    progressDialog.dismiss();
    if (headerCode == 1)
        activity.login(id);
    else
        activity.showLoginError("");
}
Activity Class:
    public void showLoginError(String result) {
    AlertDialog.Builder builder = new AlertDialog.Builder(InputsRecap.this);
    builder.setPositiveButton("okay",
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
    builder.setMessage("unable to upload database");
    AlertDialog alert = builder.create();
    alert.setCancelable(true);
    alert.show();

}

1 Answer 1

1

If an exception is thrown in your doInBackground method these two lines:

progressDialog.dismiss();
activity.showLoginError("");

Will cause Exception - you can not modify the UI from within the doInBackground method. Instead set a flag and show the error dialog in the onPostExecute which is executed in the main thread.

Check the link below especially the topic under heading The 4 steps.

http://developer.android.com/reference/android/os/AsyncTask.html

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.