Consume WebService C # on android

0

I have a Web Service created in C # where I access a certain method to authenticate a teacher, if the user data and password passed through parameters exist 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 all code accessing the web service and returning this data is in the Activity class.

I would like to know if you have how I can structure my classes to stay more organized.

Example:

  • Teacher class: Where will contain all the teacher's get and set attributes and methods.

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

  • Activity class responsible for capturing the typed data and passing it 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();

        }


}
    
asked by anonymous 30.08.2016 / 04:04

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 best I suggest you follow the following architecture:

  • LoginActivity: Only initializes view components and registers listeners.
  • LoginOnClickListener: Handles the OnClick event by calling methods that perform business logic through a facade.
  • SOAPController: Facade for business methods that handle SOAP services.
  • GenericSOAP: Abstract implementation or interface of a SOAP that defines the format of your SOAP classes.
  • LogonSOAP: Calls the logon service
  • JSONObject: Converts JSONObject data to users
  • User: Encapsulates a user's data: code, name, user, and password
  • AsyncTask: Implements the asynchronous task call. Remember that class names should begin with the first capital letter. ^
  • Then, it would look more or less like this:

    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
    }
    

    Did you realize how many responsibilities your activity had? When you need to use an "e" to quote them, it's a sign that they need refactoring. I suggest that during refactoring you adopt baby-steps, go testing the code with each step and understand what is being done in steps.

    I hope I have helped ^^

        
    01.09.2016 / 13:19