Android, AsyncTask con kSoap2
Estoy codificando una aplicación que utiliza principalmente los datos obtenidos de un servicio web, y quiero usar AsyncTask para ejecutar las llamadas SOAP en el fondo … Soy bastante nuevo para Android (siendo un programador iOS), así que ' Soy un poco nuevo en esto …
Ahora, tengo una pantalla de inicio de sesión, donde tomo un inicio de sesión proporcionado por el usuario y comprobarlo contra la información de un servidor …
- Android: SSLException Error de E / S durante la llamada al sistema, conexión agotada
- Android, KSoap2 y .NET Web Service w / parameters = Resultado NULL
- Cómo autenticar servicio web sap con ksoap2
- Cómo agregar un archivo .jar al proyecto de Android Studio (versión 0.4.0)
- ¿Cuál es el espacio de nombres, acción de jabón y url debería ser para mi aplicación Android acceder a servicio web wcf?
Así que en mi actividad de inicio de sesión:
loginBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Run the connection to authenticate the user AuthenticateConnection mAuth = new AuthenticateConnection(); mAuth.mNumber = number; mAuth.mPassword = pass; mAuth.connection(); } }
Y mi clase de jabón es la siguiente:
public class AuthenticateConnection { private static final String SOAP_ACTION = "http://tempuri.org/Authenticate"; private static final String METHOD_NAME = "Authenticate"; private static final String NAMESPACE = "http://tempuri.org/"; private String URL; public Boolean userOK; public String mNumber; public String mPassword; public AuthenticateConnection() { } public void connection() { Singleton service = Singleton.getInstance(); String firstURL = service.getURL(); URL = firstURL + "Parent.svc"; System.out.println("Connection to: " + URL); //Initialize soap request SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME); //Add parameters request.addProperty("login", mNumber); request.addProperty("password", mPassword); //Declare the version of the SOAP request SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); envelope.dotNet=true; envelope.implicitTypes=true; envelope.setAddAdornments(false); //Prepare request envelope.setOutputSoapObject(request); //Needed to make the internet call HttpTransportSE androidHttpTransport = new HttpTransportSE(URL); //Allow for debugging - needed to output the request androidHttpTransport.debug = true; try { //this is the actual part that will call the web service androidHttpTransport.call(SOAP_ACTION, envelope); //Get the SoapResult from the envelope body. //Object result = envelope.getResponse(); //Object result = envelope.bodyIn; SoapObject sResult = (SoapObject)envelope.bodyIn; String tempID = sResult.getProperty("AuthenticateResult").toString(); //Check if the user exists and has the correct password if(tempID != "-1") { userOK = true; //Store the values in the singleton class service.parentID = sResult.getProperty("AuthenticateResult").toString(); service.parentToken = sResult.getProperty("token").toString(); } //If -1 is returned, then either the number or the password is incorrect else { userOK = false; } } catch(org.xmlpull.v1.XmlPullParserException ex2) { //System.out.println(androidHttpTransport.requestDump.toString()); } catch (Exception e) { e.printStackTrace(); System.out.println(androidHttpTransport.requestDump.toString()); } } }
Así que mi pregunta es, ¿cómo haría esto con AsyncTask? He estado buscando algunos tutoriales sobre AsyncTask, pero en realidad no lo he conseguido hasta ahora …
- KSoap2 y KvmSerializable-Envía el objeto de clase con un campo de lista a webservice en java android
- ¿Cómo pasar el objeto de androide a servicio web de jabón?
- Ksoap2: java.lang.IllegalArgumentException: size <= 0 mientras hace una http.call
- ¿Cómo puedo lanzar o deserializar SoapObject a mi objeto?
- No se pueden serializar las fechas con ksoap2
- Dónde ver el XML generado (KSOAP2)
- Cómo consumir servicios WCF dependientes de la sesión usando Ksoap2-Android
- ¿Cómo usar el tiempo de espera de ksoap en android?
Tu puedes hacer:
private class ConnectionTask extends AsyncTask<String, Void, Void> { private ProgressDialog dialog = new ProgressDialog(ACTIVITY_NAME.this); protected void onPreExecute() { dialog.setMessage("Connecting..."); dialog.show(); } protected void doInBackground(String... args) { AuthenticateConnection mAuth = new AuthenticateConnection(); mAuth.mNumber = args[0]; mAuth.mPassword = args[1]; mAuth.connection(); } protected void onPostExecute(Void v) { if (dialog.isShowing()) { dialog.dismiss(); } } }
Y luego lo llaman:
loginBtn.setOnClickListener(new OnClickListener() { public void onClick(View v) { //Run the connection to authenticate the user new ConnectionTask().execute(number, pass); } }
Su método de connection
en AuthenticateConnection
debe devolver algo para garantizar que el usuario ha sido autenticado. Entonces usted puede utilizar ese valor en el onPostExecute
, algo como esto:
protected void onPostExecute(Integer res) { if (dialog.isShowing()) { dialog.dismiss(); } if (res.intValue() == OK) { /* Maybe start a new Activity ...*/ } else { /* Maybe show a Toast with an error message ...*/ } }
En este caso, la firma del asynctask cambiará: private class ConnectionTask extends AsyncTask<String, Void, Integer>
y doInBackground devolverá un Integer
.
Espero eso ayude.
- Cómo utilizar la consulta para el argumento de selección múltiple utilizando una columna de selección
- Servidor para la notificación de empuje de GCM a android en C #