MastErAldo MastErAldo - 6 months ago 12
Android Question

General purpose network manager in Android

I'm working on an Android project (API level 10) which needs to send and receive http messages to/from a server.

I implemented a class named NetworkManager which provides different methods, one for each http request (e.g.: loginRequest(user pass), RegistrationRequest(user.....) ).

All these methods generates a JSON object that is passed to the method called sendMessage, which is the method that actually establish the connection, sends and receives the response (also a json object).

Of course network calls are time consuming, so i first decided to use an AsyncTask to display a progressDialog while the network operation is being performed.

The problem is that i need to get the response value retrived from the background thread before executing any other operation which involves the result itself done by the Main thread.
At the same time i would like to make a common and reusable implementation of the AsyncTask.

E.g.: I have a login activity which shows 2 EditText (username, password) and a button called Login. When I press the login button, a progressDialog must appear, and must be disposed once the doInBackground task is accomplished. Of course i could do this way:

onClick(View v) //called when the login button is pressed
{
onPreExecute()
{
//Show the progress dialog
}

doInBackground()
{
//Retreive the login response (an integer containing a message code) using sendLoginRequest(username, password);
//return the response
}

onPostExecute(int response)
{
//Dispose the progress dialog, then loginSucessfull ? start new activity : show error toast
}
}


But, doing this way i should implement an async task for every request i need to send which is what i would like to avoid because if i have N requests i should create N classes that extend AsyncTask.

Thank you!

Answer

What i would suggest you is to use INTERFACES for handling response of http request.

The background thread either it be a AysncTask or it be Thread needs to handle both

  • response

  • exception

Think it like this way

MainThread - Hey Background Thread do this operation and let me know when you are done.

MainThread - Ok till Background Thread executes its operation let me show progress dialog.

BackGroundThread - I am done with my work. hey MainThread here catch you response or exception

MainThread - Let me stop showing progress bar.

So we need to simulate this callback mechanism via code and also needs to take care that we implement a reusable architecture.

Something like this

Define a Interface

public interface HttpRequestResponse {
    public void onSuccess(HttpResponse response);
    public void onException(Exception exception); 
}     


class HttpRequestResponseHandler {

   private ActionItem action;
   private HttpRequestResponse hrr;
   private Executor executor; 

   public enum ActionItem {
      LOGIN_REQUEST ,
      REGISTRATION_REQUEST            
   } 

   public HttpRequestResponseHandler(ActionItem action, HttpRequestResponse hrr) {
      this.action = action;
      this.hrr = hrr;       
   }

   public void execute(){
     executor = new Executor();
     executor.execute();       
   }

   private class Executor extends AsyncTask<Void,Void,Void> {

      @Override
      public Void doInBackground() {
         switch(action) {

            case LOGIN_REQUEST : doLogin();
                                 break;   

            case REGISTRATION_REQUEST : doRegistration();
                                        break; 
         }
      }
   }

   private void doLogin() {

      HttpResponse response = null;
      Exception exception = null;
      try {
         response = makeHttpRequestHere();
      } catch (Exception e) {
         exception = e;
      }

      if(exception != null) {
         hrr.onException(exception);
      } else {
         hrr.onSuccess(response);
      }

   }   

}

Now in somewhere in your activity code file do like this.

 HttpRequestResponse hrr = new HttpRequestResponse(){

    @Override
    public void onSuccess(HttpResponse response) {
       hideProgressDialog();
       handleResponse(response);
    }

    @Override
    public void onException(Exception exception) {
       hideProgressDialog();
       showErrorDialog(exception.getMessage());
    } 
 }

 HttpRequestResponseHandler hrrh = new HttpRequestResponseHandler(ActionItem.LOGIN_REQUEST,hrr);
 hrrh.execute();
 showProgressDialog();  

Hope all this lead to what you want. Its been a long answer and took quite a effort of mine to figure. :)

Comments