turtleboy
turtleboy

Reputation: 7574

Android how to handle network exception from inside AsyncTask

I am calling a webservice from an AsyncTask. It works fine but i'm trying to test it when i've turned the phone's mobile network off. This is to replicate the user having no signal.

here's the code.

 @Override
        protected Void doInBackground(String... params) {

            try {
                Log.e(TAG, "inside doInBackground");


                rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);


            } catch (Exception e) {

                Log.e(TAG, "there's a problem");

               e.printStackTrace();


            }
            return null;

        }

The log statement is never logged out to logcat enev though a java.net.ConnectionException is thrown. How can i deal with potentially not having a network signal and gracefully exit the app or even better call the activities oncreate again?

Upvotes: 2

Views: 7470

Answers (2)

Ron
Ron

Reputation: 24235

Do somthing like this

// this is inner to activity class
class MyAsyncTask extends AsyncTask {
...
    @Override
    protected Void doInBackground(String... params) {

        try {
            Log.e(TAG, "inside doInBackground");
            rotaArray = nfcscannerapplication.loginWebservice.getRota(params[0], params[1]);

        } catch (IOException e) {
           HandleNetworkError(e);
           e.printStackTrace();
        }
        return null;

    }
}
// Some where in your activity class.
void HandleNetworkError(Exception e) {
    // Do whatever with the exception message, eg display it in a dialog.
    ...
}

Upvotes: 0

PrasadW
PrasadW

Reputation: 427

I believe you want to provide some message or work out something in case of a network failure....If that is the case then you need to check whether your device has an active network connection....

I think this link will help...:)

Upvotes: 1

Related Questions