To use the tutorial in android 4.0.3 if had to work with AsynxTasc but i still dont work?
Asked Answered
C

2

-4

I used this tutorial and did some changes that it should work for android 4.0.3.

But it still doesn't.

Can someone post me a correct solution?

package com.webservice;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.app.Activity;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;


public class FirstScreen extends Activity

{
/** Called when the activity is first created. */

private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
private static String SOAP_ACTION2 = "http://tempuri.org/CelsiusToFahrenheit";
private static String NAMESPACE = "http://tempuri.org/";
private static String METHOD_NAME1 = "FahrenheitToCelsius";
private static String METHOD_NAME2 = "CelsiusToFahrenheit";
private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
Button btnFar,btnCel,btnClear;
EditText txtFar,txtCel;

@Override
public void onCreate(Bundle savedInstanceState)

{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_first_screen); 
        btnFar = (Button)findViewById(R.id.btnFar);
        btnCel = (Button)findViewById(R.id.btnCel);
        btnClear = (Button)findViewById(R.id.btnClear);
        txtFar = (EditText)findViewById(R.id.txtFar);
        txtCel = (EditText)findViewById(R.id.txtCel);
        
        btnFar.setOnClickListener(new View.OnClickListener()
        {
                 @Override
                  public void onClick(View v)
                  {
                      new one1().execute();
                  }
            });            
        btnCel.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                      new one2().execute();
                  }
            });
        
        btnClear.setOnClickListener(new View.OnClickListener()
        {
                  @Override
                  public void onClick(View v)
                  {
                        txtCel.setText("");
                        txtFar.setText("");
                  }
            });     
 }
    
private class one1 extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... arg0) {
        // TODO Auto-generated method stub
           //Initialize soap request + add parameters
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);    
      
        //Use this to add parameters
        request.addProperty("Fahrenheit",txtFar.getText().toString());         

        //Declare the version of the SOAP request
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);          

        envelope.setOutputSoapObject(request);
        envelope.dotNet = true;         

        try {
              HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);                

              //this is the actual part that will call the webservice
              androidHttpTransport.call(SOAP_ACTION1, envelope);
             
              // Get the SoapResult from the envelope body.
              SoapObject result = (SoapObject)envelope.bodyIn;
              if(result != null)
              {
                    //Get the first property and change the label text
                    txtCel.setText(result.getProperty(0).toString());
              }
              else
              {
                    Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
              }
        } catch (Exception e) {

              e.printStackTrace();

        }           
        return null;
    }
    
}

private class one2 extends AsyncTask<String, Integer, String> {

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        //Initialize soap request + add parameters
  SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME2);     

  //Use this to add parameters
  request.addProperty("Celsius",txtCel.getText().toString());     

  //Declare the version of the SOAP request
  SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);    

  envelope.setOutputSoapObject(request);
  envelope.dotNet = true;   

  try {
        HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);          

        //this is the actual part that will call the webservice
        androidHttpTransport.call(SOAP_ACTION2, envelope);          

        // Get the SoapResult from the envelope body.            
        SoapObject result = (SoapObject)envelope.bodyIn;            
        if(result != null)
        {
              //Get the first property and change the label text
              txtFar.setText(result.getProperty(0).toString());

        }
        else
        {

              Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();

        }
  } catch (Exception e) {
        e.printStackTrace();
  }         return null;
    }
    
}
}

Errorlog and Code

private class one1 extends AsyncTask<String, Integer, SoapObject> {

protected SoapObject doInBackground(String... arg0) {

protected **void** onPreExecute(**)**
 {
     //value from textview/edittext
 }

// TODO Auto-generated method stub
   //Initialize soap request + add parameters
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);    

//Use this to add parameters
request.addProperty("Fahrenheit","30");// provide value here        

//Declare the version of the SOAP request
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);          

envelope.setOutputSoapObject(request);
envelope.dotNet = true;         

try {
      HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);                
      androidHttpTransport.call(SOAP_ACTION1, envelope);
      **result** = (SoapObject)envelope.bodyIn;

} catch (Exception e) {

      e.printStackTrace();

}           
return **result**;
   }

   protected void onPostExecute(SoapObject result)
   {
if(result != null)
{
  System.out.println(result.getProperty(0).toString());
}
else
{
  Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
}

}
}

I'm getting the following syntax error:

Syntax error, insert "enum Identifier" to complete EnumHeader Syntax error on token "void", @ expected result cannot be resolved to a variable FirstScreen.java result cannot be resolved to a variable FirstScreen.java

Edited Code :

package com.webservice;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.view.View;
import android.view.View.OnClickListener;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;



public class FirstScreen extends Activity
{


     private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
     private static String NAMESPACE = "http://tempuri.org/";
     private static String METHOD_NAME1 = "FahrenheitToCelsius";
     private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
     SoapObject result;
     Button b;
     EditText et;
     int value;
     TextView tv;
     ProgressDialog pd;

     @Override
      public void onCreate(Bundle savedInstanceState)
      {

        super.onCreate(savedInstanceState);
        pd= new ProgressDialog(this);
        pd.setTitle("Making Soap Request");
        setContentView(R.layout.activity_first_screen); 
        b= (Button) findViewById(R.id.button1);
        tv= (TextView) findViewById(R.id.textView2);
        et= (EditText) findViewById(R.id.ed);           
                b.setOnClickListener(new OnClickListener()
                {

               @Override
               public void onClick(View v) {
               // TODO Auto-generated method stub
                value=Integer.parseInt(et.getText().toString());
                new one1().execute();
        }
    });


    }

     private class one1 extends AsyncTask<String, Integer, SoapObject> {

      protected void onPreExecute()
      {
          pd.show();
      }
    protected SoapObject doInBackground(String... arg0) {
        // TODO Auto-generated method stub
           //Initialize soap request + add parameters
        SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);    

        //Use this to add parameters
        request.addProperty("Fahrenheit",value);         

        //Declare the version of the SOAP request
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);          

        envelope.setOutputSoapObject(request);
        envelope.dotNet = true;         

        try {
              HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);                
              androidHttpTransport.call(SOAP_ACTION1, envelope);
              result = (SoapObject)envelope.bodyIn;

        } catch (Exception e) {

              e.printStackTrace();

        }           
        return result;
    }

     protected void onPostExecute(SoapObject result)
     {
      pd.dismiss();
    if(result != null)
    {
          tv.setText("Result = "+result.getProperty(0).toString());
    }
    else
    {
          Toast.makeText(getApplicationContext(), "No       Response",Toast.LENGTH_LONG).show();
    }
    }

    }
}
Clubhaul answered 20/3, 2013 at 11:4 Comment(7)
what is the error you are getting ?Horsepower
Did you install the apk ? Are you connected to the internet ?Stigmasterol
onPreExecute() is inside doInbackground(). It has to be outside.developer.android.com/reference/android/os/AsyncTask.html. Look at the documentation.Handshake
You have not declared SoapObject result in FirstScreen.java.Handshake
@Clubhaul i have edited the question. 1. u imported wrong listener. 2.u had set button ontouchlistener.3. u had implemented dialog on click listener rather than button click listener. Check the question edit and use the same should work now.Handshake
@Clubhaul did u try the edited answer in the questionHandshake
Typo: one method inside another: protected SoapObject doInBackground(String... arg0) { protected **void** onPreExecute(**)**Apanage
H
0

You are updating UI in the background thread. You have to update UI on the UI thread.

Return result in doInBackground()

In onPostExecute() update ui.

   Void onPostExecute(int result)  
   {
       if(result != null)
    {
          txtFar.setText(result.getProperty(0).toString());

    }
    else
    {

     Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();

    }
 }

http://developer.android.com/reference/android/os/AsyncTask.html. Look at the link especially the topic under The 4 steps.

In your Activity.

new SoapRequestTask().execute();//call asyntask from ui.


private class SoapRequestTask extends AsyncTask<Void, Void, Long> {

 protected void onPreExecute() {
     //display progress dialog
 }

 protected Long doInBackground(Void... params) {

   //make soap request and get result. do not update ui here.
     return result;
 }



 protected void onPostExecute(Long result) {
     //dismiss dialog. update ui here.
 }
}

http://10keyes.blogspot.in/2012/08/android-implement-ksoap2-in-asynctask.html. A tutorial of asynctask and ksoap.

Edit

 public class FirstScreen extends Activity
 {
 private static String SOAP_ACTION1 = "http://tempuri.org/FahrenheitToCelsius";
 private static String NAMESPACE = "http://tempuri.org/";
 private static String METHOD_NAME1 = "FahrenheitToCelsius";
 private static String URL = "http://www.w3schools.com/webservices/tempconvert.asmx?WSDL";
SoapObject result;
 Button b;
 EditText et;
 int value;
 TextView tv;
 ProgressDialog pd;

 @Override
  public void onCreate(Bundle savedInstanceState)
  {

    super.onCreate(savedInstanceState);
    pd= new ProgressDialog(this);
    pd.setTitle("Making Soap Request");
    setContentView(R.layout.activity_main); 
    b= (Button) findViewById(R.id.button1);
    tv= (TextView) findViewById(R.id.textView2);
    et= (EditText) findViewById(R.id.ed);
    b.setOnClickListener(new OnClickListener()
    {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            value=Integer.parseInt(et.getText().toString());
            new one1().execute();
        }

    });


}

 private class one1 extends AsyncTask<String, Integer, SoapObject> {

  protected void onPreExecute()
  {
      pd.show();
  }
protected SoapObject doInBackground(String... arg0) {
    // TODO Auto-generated method stub
       //Initialize soap request + add parameters
    SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);    

    //Use this to add parameters
    request.addProperty("Fahrenheit",value);         

    //Declare the version of the SOAP request
    SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);          

    envelope.setOutputSoapObject(request);
    envelope.dotNet = true;         

    try {
          HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);                
          androidHttpTransport.call(SOAP_ACTION1, envelope);
          result = (SoapObject)envelope.bodyIn;

    } catch (Exception e) {

          e.printStackTrace();

    }           
    return result;
}

 protected void onPostExecute(SoapObject result)
 {
  pd.dismiss();
if(result != null)
{
      tv.setText("Result = "+result.getProperty(0).toString());
}
else
{
      Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();
}
}

}

My activity_main.xml

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:text="FahrenheitToCelsius" />

<EditText
    android:id="@+id/ed"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_marginTop="43dp" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="37dp"
    android:text="MakeRequest" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center"
    android:layout_marginTop="20dp"
    android:text="Result" />

 </LinearLayout>

Result on my phone.

enter image description here

Handshake answered 20/3, 2013 at 11:13 Comment(11)
check the edit. Do not update ui from doInBackground(). I removed buttons and textview and tested the code and it works. I provided the parameter as 30. Do not get value from textview/ edittext in doInbackground.Handshake
Doesent work.. i have errors at result and protected void onPreExecute(){}Clubhaul
pls check the edit and the reuslting snapshot. Snapshot taken on my phone and it works. Included layout code.Handshake
post the code and try the edit code, it works on my phone and i have put a snap shot of the same. Post the error that your getting.Handshake
Hey! I get errors! At this part of the code: b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub value=Integer.parseInt(et.getText().toString()); new one1().execute(); }Clubhaul
b.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub value=Integer.parseInt(et.getText().toString()); new one1().execute(); } });. Must be a syntax error missing parathesis. Try this and check if value is declared in the class.Handshake
u have imported the wrong listener. import android.view.View; import android.view.View.OnClickListener;.Handshake
Remove import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; and Import view's on click listener. that is why u are getting errors.Handshake
still getting errors??. Also remove @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub }Handshake
Thx! but i still have the same error as befor. but now the @Override public void onClick(DialogInterface arg0, int arg1) { // TODO Auto-generated method stub } is also wrong! I dont understand why im getting errors wiht the same code witch is working at your computer...Clubhaul
you have to implement button click listener so you have to remove that part of the code. I edited the question with the working answer. pls check the edit code.. get you basics right by reading the docs at developer site.Handshake
O
0

You can not access any UI elements in th DoInBackground() method, as it runs on its own thread, not on the UI thread. You should use

txtFar.setText(result.getProperty(0).toString());

and

Toast.makeText(getApplicationContext(), "No Response",Toast.LENGTH_LONG).show();

call in the onPostExecute, or in onProgressChanged() methods.

Outlive answered 20/3, 2013 at 11:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.