Rodrigo Salgado Atala
Rodrigo Salgado Atala

Reputation: 344

How to handle different method calls to web service in the same class using AsyncTask?

I'm developing an Android app, which is supposed to connect to a web service and save data into the app's local database. I'm using AsyncTask to connect to said web service from my "Login" class, which then returns the result to the processFinish method in "Login." The problem is that I need to separate the data I bring in several methods in the web service, and as far as I have seen, the result is always handled by processFinish. This is a problem because I'll need to handle the data differently depending on the method I call.

Is there a way to tell processFinish which method in my web service I called, so it can handle the result differently? I thought about sending the method's name from the web service itself as part of the result, but it feels forced, and I was hoping to do this in a cleaner way.

Here's the code I'm using:

LoginActivity.java (shortened):

public class LoginActivity extends ActionBarActivity implements AsyncResponse {

    public static DBProvider oDB;
    public JSONObject jsonObj;

    public JSONObject jsonUser;

    WebService webService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        oDB = new DBProvider(this);
    }
    /*Function that validates user and password (on button press).*/
    public void validateLogin(View view){

        ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE);

        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

        if (!isConnected){
            Toast.makeText(this, "No connection!", Toast.LENGTH_LONG).show();
        }else{

            /* params contains the method's name and parameters I send to the web service. */
            String[][][] params = {
                {
                    {"MyWebServiceMethod"}
                },
                {
                    {"user", "myUserName", "string"},
                    {"pass", "myPass", "string"}
                }
            };

            try{
                webService = new WebService();
                webService.delegate = this;
                webService.execute(params);
            }catch(Exception ex){
                Toast.makeText(this, "Error!: " + ex.getMessage(), Toast.LENGTH_LONG).show();
            }
        }

    }

    public void processFinish(String result){
        try{
            // Here I handle the data in "result"

            }
        }catch(JSONException ex){
            Toast.makeText(this, "JSONException: " + ex.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

}

WebService.java:

public class WebService extends AsyncTask<String[][][], Void, String> {

    /**
     * Variable Declaration................
     * 
     */
    public AsyncResponse delegate = null;
    String namespace = "http://example.net/";
    private String url = "http://example.net/WS/MyWebService.asmx";

    public String result;

    String SOAP_ACTION;
    SoapObject request = null, objMessages = null;
    SoapSerializationEnvelope envelope;
    HttpTransportSE HttpTransport;

    /**
     * Set Envelope
     */
    protected void SetEnvelope() {

        try {
            // Creating SOAP envelope
            envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            //You can comment that line if your web service is not .NET one.
            envelope.dotNet = true;

            envelope.setOutputSoapObject(request);
            HttpTransport = new HttpTransportSE(url);
            HttpTransport.debug = true;

        } catch (Exception e) {
            System.out.println("Soap Exception---->>>" + e.toString()); 
        }
    }

    @Override
    protected String doInBackground(String[][][]... params) {
        // TODO Auto-generated method stub
        try {
            String[][][] data = params[0];

            final String methodName = data[0][0][0];
            final String[][] arguments = data[1];

            SOAP_ACTION = namespace + methodName;

            //Adding values to request object
            request = new SoapObject(namespace, methodName);

            PropertyInfo property;

            for(int i=0; i<arguments.length; i++){
                property = new PropertyInfo();
                property.setName(arguments[i][0]);
                property.setValue(arguments[i][1]);

                if(arguments[i][2].equals("int")){
                    property.setType(int.class);
                }
                if(arguments[i][2].equals("string")){
                    property.setType(String.class);
                }
                request.addProperty(property);
            }

            SetEnvelope();

            try {
                //SOAP calling webservice
                HttpTransport.call(SOAP_ACTION, envelope);

                //Got Webservice response
                result = envelope.getResponse().toString();

            } catch (Exception e) {
                // TODO: handle exception
                result = "Catch1: " + e.toString() + ": " + e.getMessage();
            }
        } catch (Exception e) {
            // TODO: handle exception
            result = "Catch2: " + e.toString();
        }

        return result;
    }

    @Override
    protected void onPostExecute(String result) {
        delegate.processFinish(result);
    }
    /************************************/
}

AsyncResponse.java:

public interface AsyncResponse {
    void processFinish(String output);
}

Upvotes: 0

Views: 616

Answers (1)

You can use different AsyncResponse classes. Anonymous classes make this more convenient:

// in one place
webService.delegate = new AsyncResponse() {
    @Override
    void processFinish(String response) {
        // do something
    }
};

// in another place
webService.delegate = new AsyncResponse() {
    @Override
    void processFinish(String response) {
        // do something else
    }
};

Upvotes: 1

Related Questions