Consume Webservice C# on android

Asked

Viewed 443 times

0

I have a Web Service created in C# where I access a certain method to authenticate a teacher, if the user and password data passed through parameters exiting in the database the web service returns me the following data [Codprof],[name],[User], [Password].

I am able to pass these parameters through a login activity perfectly and all data is being returned.

The problem is that the entire web service access and return code for this data is in the Activity class.

I wonder if there’s a way I can structure my classes to be more organized.

Example:

  • Teacher Class: Where all teacher’s get and set attributes and methods will be contained.

  • Professorws class: Where you will receive the parameters of Activity and communicate with the web service returning an object of the teacher type.

  • Activity class responsible for capturing typed data and passing to Professorws.

Code:

package feol.com.br.diarioescolar;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;

public class Login extends Activity {


    private Button btEntrar;
    private EditText edUsuario, edSenha;

    private ProgressDialog dialogo;
    String codigo;
    String nome;
    String usuario ;
    String senha ;


    private static String SOAP_ACTION ="http://feol/AutenticarProfessor";
    private static String NAMESPACE = "http://feol/";
    private static String METHOD_NAME= "AutenticarProfessor";
    private static String URL = "http://192.168.43.175/ServiceFeol.asmx?WSDL";


    Professor p = new Professor();
    ProfessorWs ws = new ProfessorWs();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        btEntrar = (Button)findViewById(R.id.btEntrar);
        edUsuario = (EditText)findViewById(R.id.edUsuario);
        edSenha = (EditText)findViewById(R.id.edSenha);

        btEntrar.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                btEntrarOnClick();

            }

        });


    }


    private void  btEntrarOnClick(){
        new asynProf().execute();

    }

    public Boolean invocaWs(){

        Boolean re = true;

        try{
             SoapObject resposta = new SoapObject(NAMESPACE,METHOD_NAME);
             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
             envelope.dotNet = true;
             resposta.addProperty("user",edUsuario.getText().toString());
             resposta.addProperty("senha",edSenha.getText().toString());
             envelope.setOutputSoapObject(resposta);


             HttpTransportSE http = new HttpTransportSE(URL);
             http.call(SOAP_ACTION,envelope);

            String resultado = envelope.getResponse().toString();
            JSONArray jsonArray = new JSONArray(resultado);


            for(int i=0;i<jsonArray.length();i++ ) {
                JSONObject jsonObject =jsonArray.getJSONObject(i);

                codigo = jsonObject.getString("CodProf");
                nome = jsonObject.getString("Nome");
                usuario = jsonObject.getString("Usuario");
                senha = jsonObject.getJSONObject("Senha").toString();
            }

        } catch (IOException e){
            e.printStackTrace();
            re=false;
        }catch (XmlPullParserException e){
            e.printStackTrace();
            re=false;
        }catch (JSONException e){
            e.printStackTrace();
        }

        return re;

    }

    class asynProf extends AsyncTask<String,String,String> {


        @Override
        protected void onPreExecute(){

            dialogo = new ProgressDialog(Login.this);
            dialogo.setMessage("Carregando codigo...");
            dialogo.setIndeterminate(false);
            dialogo.setCancelable(false);
            dialogo.show();
        }

        @Override
        protected String doInBackground (String... strings){
            if (invocaWs())
            {return "ok";

            }else {return "erro";}

        }

        @Override
        protected void onPostExecute(String s){
            dialogo.dismiss();
            if(s.equals("ok")){
                mostraCod();
            }else {
                Log.e("Script","DeuErrado" + s.toString());}

        }
    }



    public void mostraCod(){
            Toast t = Toast.makeText(getBaseContext(),"Código pro: " +nome, Toast.LENGTH_SHORT);
            t.show();

        }


}

1 answer

2

Come on, first you need to define the responsibilities of your program. Clearly this Activity has many responsibilities, so to structure it better I suggest you follow the following architecture:

  1. Loginactivity: Just initialize the view components and register listeners.
  2. Loginonclicklistener: Treats the Onclick event by calling the methods that realize business logic through a facade.
  3. Soapcontroller: Facade for business methods handling SOAP services.
  4. Genericsoap: Abstract implementation or interface of a SOAP that establishes the format of your SOAP classes.
  5. Logonsoap: Call the logon service
  6. Usuariojsonobject: Converts Jsonobject data to users
  7. User: Encapsulates a user’s data: code, name, user, and password
  8. Asynctask: Implements the asynchronous task call. Remembering which class names should start with the first uppercase letter.^

So it would be more or less like this division:

class LoginActivity {
    + onCreate
    + mostrarCod
    + carregarComponentes
    + carregarListeners
}

class LoginOnClickListener {
    + btEntrarOnClick
}

class SOAPController {
    + logar
}

interface GenericSOAP {
    + invocarWS
}

class LogonSOAP {
    + invocarWS
}

class UsuarioJSONObject {
    + converterJSONObjectParaUsuario
}

// É um POJO
class Usuario {
}

class AsyncTask {
    // Contrutor precisa receber a activity para iniciar a Dialog.
    // É importante iniciar a Dialog em uma thread separada (runOnUiThread).
    + AsyncTask (Activity activity)
    + onPreExecute
    + doInBackground
    + onPostExecute
}

Have you noticed how many responsibilities your Activity has? When you need to use an "and" to quote them, it’s already a sign that they need refactoring. I suggest that during refactoring you adopt baby-Steps, go testing the code at every step and understand what is being done by steps.

I hope I’ve helped ^^

Browser other questions tagged

You are not signed in. Login or sign up in order to post.