mercredi 25 janvier 2017

How to create a common AsyncTask class for webservice call in an android app?

I am trying to write a common webservice class where in any of the activities within my application has to point to this common class for webservice stuff. Currently I got stuck in between i.e; to pass the success/failure message to the calling class, My current implementation is like below, I have an interface class where in I have 2 methods,

 public void webServiceReqExecutedSuccessfully();
 public void webSerReqFailed();

and each webservice calling class implements these methods as per their requirements. And my common webservice class is like below,

    public class WebServiceRequest extends AsyncTask < String, Void, Boolean> 
    {
            
        private static final MediaType FORM_DATA_TYPE = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");
            
            public enum HTTPServiceTags {
            
          POST_IT,
          GET_ALL_ITEMS
         }

         HTTPServiceTags requestTag;
         public ATWebServiceRequest(HTTPServiceTags reqTag, Callable < Void > _ServiceResponseSuccess, Callable < Void > _ServiceResponseFailure) {
          this.requestTag = reqTag;
         }

         @Override
         protected Boolean doInBackground(String...postDataSet) {
          Boolean result = true;
          String requestURL = postDataSet[0];
          String postBody = getPostBody(postDataSet);
          Log.d(requestURL, postBody);
          try {
           OkHttpClient client = new OkHttpClient();
           RequestBody body = RequestBody.create(FORM_DATA_TYPE, postBody);
           Request request = new Request.Builder().url(requestURL).post(body).build();
           Response response = client.newCall(request).execute();
          } catch (IOException exception) {
           result = false;
          }
          return result;
         }

         @Override
         protected void onPostExecute(Boolean result) {
          if (result) {
           switch (requestTag) {
            case POST_IT:
//HOW CAN I NOTIFY/INVOKE webServiceReqExecutedSuccessfully METHOD OF THE CALLING CLASS HERE??? 
             break;
            case GET_ALL_ITEMS:
             break;
            default:
             break;
           }
          }
         }
        }

My question here is after the service call response how can I notify/invoke the calling class interface methods(webServiceReqExecutedSuccessfully() / webSerReqFailed()) from which object reference? Any help is appreciated in advance. Thanks

Aucun commentaire:

Enregistrer un commentaire