Foros del Web » Programando para Internet » Android »

[SOLUCIONADO] Cómo consumir WebService en otro hilo?

Estas en el tema de Cómo consumir WebService en otro hilo? en el foro de Android en Foros del Web. Que tal, Soy nuevo en el desarrollo Android, he comenzado realizando una aplicación que consume un WebService, es bastante sencillo, me ayude de la biblioteca ...
  #1 (permalink)  
Antiguo 28/05/2013, 13:31
Avatar de RodMoreno  
Fecha de Ingreso: abril-2013
Ubicación: México
Mensajes: 4
Antigüedad: 11 años
Puntos: 0
Pregunta Cómo consumir WebService en otro hilo?

Que tal,

Soy nuevo en el desarrollo Android, he comenzado realizando una aplicación que consume un WebService, es bastante sencillo, me ayude de la biblioteca ksoap2-android.

MainActivity.java
Código Java:
Ver original
  1. package name.rodmoreno.webservice;
  2.  
  3. import android.os.Bundle;
  4. import android.app.Activity;
  5. import android.view.Menu;
  6. import android.widget.TextView;
  7. import android.widget.EditText;
  8. import android.view.View;
  9.  
  10. import org.ksoap2.SoapEnvelope;
  11. import org.ksoap2.serialization.SoapObject;
  12. import org.ksoap2.serialization.SoapSerializationEnvelope;
  13. import org.ksoap2.transport.HttpTransportSE;
  14.  
  15. public class MainActivity extends Activity {
  16.  
  17.     @Override
  18.     protected void onCreate(Bundle savedInstanceState) {
  19.         super.onCreate(savedInstanceState);
  20.         setContentView(R.layout.activity_main);
  21.     }
  22.  
  23.  
  24.     @Override
  25.     public boolean onCreateOptionsMenu(Menu menu) {
  26.         // Inflate the menu; this adds items to the action bar if it is present.
  27.         getMenuInflater().inflate(R.menu.main, menu);
  28.         return true;
  29.     }
  30.  
  31.     public String consumirWS(String Nombre){
  32.         final String SOAP_ACTION = "urn:webserv";
  33.         final String METHOD = "saludo";
  34.         final String NAMESPACE = "urn:webserv";
  35.         final String ENDPOINTWS = "http://192.168.1.65/servicio.php";
  36.         String respuesta = null;
  37.  
  38.         try{
  39.             SoapObject userRequest = new SoapObject(NAMESPACE, METHOD);
  40.             userRequest.addProperty("nombre", Nombre);
  41.  
  42.             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  43.             envelope.setOutputSoapObject(userRequest);
  44.  
  45.             HttpTransportSE androidHttpTransport = new HttpTransportSE(ENDPOINTWS);
  46.             androidHttpTransport.debug = true;
  47.             androidHttpTransport.call(SOAP_ACTION, envelope);
  48.  
  49.             respuesta = envelope.getResponse().toString();
  50.         }
  51.         catch (Exception e){
  52.             e.printStackTrace();
  53.         }
  54.  
  55.         return respuesta;
  56.     }
  57.  
  58.     public void enviarNombre(View v){
  59.         TextView textoSalida = (TextView) findViewById(R.id.salida);
  60.         EditText textoEntrada = (EditText) findViewById(R.id.entrada);
  61.  
  62.         textoSalida.setText(consumirWS(textoEntrada.getText().toString()));
  63.     }
  64.    
  65. }

activity_main.xml
Código XML:
Ver original
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.    xmlns:tools="http://schemas.android.com/tools"
  3.    android:layout_width="match_parent"
  4.    android:layout_height="match_parent"
  5.    android:paddingLeft="@dimen/activity_horizontal_margin"
  6.    android:paddingRight="@dimen/activity_horizontal_margin"
  7.    android:paddingTop="@dimen/activity_vertical_margin"
  8.    android:paddingBottom="@dimen/activity_vertical_margin"
  9.    tools:context=".MainActivity">
  10.  
  11.     <EditText
  12.            android:layout_width="wrap_content"
  13.            android:layout_height="wrap_content"
  14.            android:inputType="textPersonName"
  15.            android:text="Rodrigo"
  16.            android:ems="10"
  17.            android:id="@+id/entrada" android:layout_alignParentBottom="true" android:layout_alignParentLeft="true"
  18.            android:layout_toLeftOf="@+id/boton"/>
  19.     <Button
  20.            android:layout_width="wrap_content"
  21.            android:layout_height="wrap_content"
  22.            android:text="Enviar"
  23.            android:id="@+id/boton" android:layout_alignParentBottom="true" android:layout_alignParentRight="true"
  24.            android:onClick="enviarNombre"/>
  25.     <TextView
  26.            android:layout_width="wrap_content"
  27.            android:layout_height="wrap_content"
  28.            android:textAppearance="?android:attr/textAppearanceLarge"
  29.            android:text="Hola..."
  30.            android:id="@+id/salida" android:layout_centerVertical="true" android:layout_alignLeft="@+id/entrada"
  31.            android:layout_alignRight="@+id/boton"/>
  32. </RelativeLayout>


En el camino me encontré con un problema yo estaba usando la API 16 y no se ejecutaba y leyendo un poco encontré que desde la API 11 en adelante las conexiones debía hacerlas en otro hilo, por ello mi app no funcionaba.

Quisiera saber, como hacer el mismo ejemplo, pero haciendo la conexión en otro hilo, intenté haciendolo así, pero no conseguí nada.

MainActivity.java
Código Java:
Ver original
  1. package name.rodmoreno.webservice3;
  2.  
  3. import android.os.Bundle;
  4. import android.os.AsyncTask;
  5. import android.app.Activity;
  6. import android.view.Menu;
  7. import android.view.View;
  8. import android.widget.TextView;
  9. import android.widget.EditText;
  10.  
  11. import org.ksoap2.SoapEnvelope;
  12. import org.ksoap2.serialization.SoapObject;
  13. import org.ksoap2.serialization.SoapSerializationEnvelope;
  14. import org.ksoap2.transport.HttpTransportSE;
  15.  
  16. public class MainActivity extends Activity {
  17.     TextView textoSalida;
  18.     EditText textoEntrada;
  19.  
  20.     @Override
  21.     protected void onCreate(Bundle savedInstanceState) {
  22.         super.onCreate(savedInstanceState);
  23.         setContentView(R.layout.activity_main);
  24.  
  25.         textoSalida = (TextView) findViewById(R.id.salida);
  26.         textoEntrada = (EditText) findViewById(R.id.entrada);
  27.     }
  28.  
  29.     @Override
  30.     public boolean onCreateOptionsMenu(Menu menu) {
  31.         // Inflate the menu; this adds items to the action bar if it is present.
  32.         getMenuInflater().inflate(R.menu.main, menu);
  33.         return true;
  34.     }
  35.  
  36.     public void botonClick(View v){
  37.         new consumirWS().execute(textoEntrada.getText().toString());
  38.     }
  39. }
  40.  
  41. public class consumirWS extends AsyncTask<String, Void, Void> {
  42.  
  43.     final String SOAP_ACTION = "urn:webserv";
  44.     final String METHOD = "saludo";
  45.     final String NAMESPACE = "urn:webserv";
  46.     final String ENDPOINTWS = "http://192.168.1.65/servicio.php";
  47.     String respuesta = null;
  48.  
  49.     protected void onPreExecute(){
  50.     }
  51.  
  52.     protected String doInBackground(String Nombre){
  53.         try{
  54.             SoapObject userRequest = new SoapObject(NAMESPACE, METHOD);
  55.             userRequest.addProperty("nombre", Nombre);
  56.  
  57.             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  58.             envelope.setOutputSoapObject(userRequest);
  59.  
  60.             HttpTransportSE androidHttpTransport = new HttpTransportSE(ENDPOINTWS);
  61.             androidHttpTransport.debug = true;
  62.             androidHttpTransport.call(SOAP_ACTION, envelope);
  63.         }
  64.         catch (Exception e){
  65.             e.printStackTrace();
  66.         }
  67.  
  68.         return respuesta;
  69.     }
  70.  
  71.     protected void onProgressUpdate(Void... values){
  72.     }
  73.  
  74.     protected void onPostExecute(Void result){
  75.         textoSalida.setText(respuesta).toString();
  76.     }
  77. }

Con este codigo solo consigo este error:
Gradle:
FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':WebService3:compileDebug'.
> Compilation failed; see the compiler error output for details.

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.
  #2 (permalink)  
Antiguo 29/05/2013, 04:29
 
Fecha de Ingreso: abril-2013
Mensajes: 12
Antigüedad: 11 años
Puntos: 0
Respuesta: Cómo consumir WebService en otro hilo?

A primera vista creo que veo varios errores:

-Lo que devuelve el doInBackground lo recibe el onPostExecute, y su tipo se define en la declaración del AsyncTask:

...extends AsyncTask<String, Void, String>...
...protected void onPostExecute(String result){

-Además, dentro del onPostExecute haces referencia a la variable respuesta, que no existe desde su contexto, deberás utilizar su parámetro result que es lo que recibe del doInBackground.

-Tampoco entiendo el toString() que haces en el onPostExecute, para mi sobra.


mira a ver si con estas indicaciones te funciona.
  #3 (permalink)  
Antiguo 29/05/2013, 10:00
Avatar de RodMoreno  
Fecha de Ingreso: abril-2013
Ubicación: México
Mensajes: 4
Antigüedad: 11 años
Puntos: 0
Respuesta: Cómo consumir WebService en otro hilo?

Muchas gracias providez, me aclaraste algunas dudas y ya se encuentra funcionando... :D

Tuviste mucha razón ademas de que me di cuenta de que instrumentaba la clase del AsyncTask fuera de la clase del Activity y debe instrumentarse dentro.

Código Java:
Ver original
  1. package name.rodmoreno.webservice4;
  2.  
  3. import android.os.AsyncTask;
  4. import android.os.Bundle;
  5. import android.app.Activity;
  6. import android.view.Menu;
  7. import android.view.View;
  8. import android.widget.EditText;
  9. import android.widget.TextView;
  10.  
  11. import org.ksoap2.SoapEnvelope;
  12. import org.ksoap2.serialization.SoapObject;
  13. import org.ksoap2.serialization.SoapSerializationEnvelope;
  14. import org.ksoap2.transport.HttpTransportSE;
  15.  
  16. public class MainActivity extends Activity {
  17.  
  18.     private EditText textoEntrada;
  19.     private TextView textoSalida;
  20.  
  21.     @Override
  22.     protected void onCreate(Bundle savedInstanceState) {
  23.         super.onCreate(savedInstanceState);
  24.         setContentView(R.layout.activity_main);
  25.  
  26.         textoEntrada = (EditText) findViewById(R.id.entrada);
  27.         textoSalida = (TextView) findViewById(R.id.salida);
  28.     }
  29.  
  30.  
  31.     @Override
  32.     public boolean onCreateOptionsMenu(Menu menu) {
  33.         // Inflate the menu; this adds items to the action bar if it is present.
  34.         getMenuInflater().inflate(R.menu.main, menu);
  35.         return true;
  36.     }
  37.  
  38.     public void clickBoton(View v)
  39.     {
  40.         new consumirWS().execute(textoEntrada.getText().toString());
  41.     }
  42.  
  43.     private class consumirWS extends AsyncTask<String, Void, String>{
  44.         final String SOAP_ACTION = "urn:webserv";
  45.         final String METHOD = "saludo";
  46.         final String NAMESPACE = "urn:webserv";
  47.         final String ENDPOINTWS = "http://192.168.1.65/servicio.php";
  48.         String respuesta = null;
  49.  
  50.  
  51.         protected String doInBackground(String... args)
  52.         {
  53.             SoapObject userRequest = new SoapObject(NAMESPACE, METHOD);
  54.             userRequest.addProperty("nombre", args[0]);
  55.  
  56.             SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
  57.             envelope.setOutputSoapObject(userRequest);
  58.  
  59.             try{
  60.                 HttpTransportSE androidHttpTransport = new HttpTransportSE(ENDPOINTWS);
  61.                 androidHttpTransport.debug = true;
  62.                 androidHttpTransport.call(SOAP_ACTION, envelope);
  63.  
  64.                 respuesta = envelope.getResponse().toString();
  65.             }
  66.             catch (Exception e){
  67.                 e.printStackTrace();
  68.             }
  69.  
  70.             return respuesta;
  71.         }
  72.  
  73.         protected void onPostExecute(String result)
  74.         {
  75.             textoSalida.setText(result);
  76.  
  77.             super.onPostExecute(String.valueOf(result));
  78.         }
  79.     }
  80.    
  81. }

Etiquetas: hilo, webservice
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta




La zona horaria es GMT -6. Ahora son las 06:33.