使用第三方之Web Service(攝氏與華氏相互轉換)

1. Download  SOAP(下列為連結下載路徑)
ksoap2-android-assembly-2.5.2-jar-with-dependencies.jar

2. Import SOAP.jar
  • 選擇路徑
  • 匯入檔案
  • 將SOAP.jar移到最上層,並且打勾

3. 程式碼實作

1. TempConvertActivity.java

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;
import android.app.Activity;
import android.app.ProgressDialog;

public class TempConvertActivity extends Activity {

    private EditText tempEt;
    private TextView tempText;
    private Switch tempSwitch;
    private Button cwsBtn;
    private static final String NAMESPACE = "http://www.w3schools.com/webservices/";
    private static final String URL = "http://www.w3schools.com/webservices/tempconvert.asmx";
    private static final String METHOD_NAME_CTF = "CelsiusToFahrenheit";
    private static final String METHOD_NAME_FTC = "FahrenheitToCelsius";
    private static final String SOAP_ACTION_CTF = "http://www.w3schools.com/webservices/CelsiusToFahrenheit";
    private static final String SOAP_ACTION_FTC = "http://www.w3schools.com/webservices/FahrenheitToCelsius";
    private String tempChoose = "celsius";
    private static final String CELSIUS_TEMP = "celsius";
    private static final String FAHRENHEIT_TEMP = "fahrenheit";
    private InputMethodManager inputMethodManager;
    private ProgressDialog progresslog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_temp_convert);
        initObject();
    }

    public void initObject() {
        tempEt = (EditText) this.findViewById(R.id.tempEt);
        tempText = (TextView) this.findViewById(R.id.tempText);
        tempSwitch = (Switch) this.findViewById(R.id.tempSwitch);
        cwsBtn = (Button) this.findViewById(R.id.cwsBtn);
        inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
        tempSwitch.setOnCheckedChangeListener(new OnCheckedChangeListener() {

            @Override
            public void onCheckedChanged(CompoundButton CompoundBtn,
                    boolean checked) {
                if (checked) {
                    tempEt.setText("");
                    tempEt.setHint("Please input fahrenheit temp");
                    tempText.setText("Celsius Temp : ");
                    tempChoose = "fahrenheit";
                } else {
                    tempEt.setText("");
                    tempEt.setHint("Please input celsius temp");
                    tempText.setText("Fahrenheit Temp : ");
                    tempChoose = "celsius";
                }
            }

        });

        cwsBtn.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View view) {
                String temp = "";
                if (!((temp = tempEt.getText().toString()).equals(""))) {
                    inputMethodManager.hideSoftInputFromWindow(
                            view.getWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);
                    new TempConvertActivity.TempTask().execute(temp);

                } else {
                    Toast.makeText(TempConvertActivity.this,
                            "Please input number", Toast.LENGTH_SHORT).show();
                }
            }

        });

    }

    private String convertTemp(String temp) throws Throwable {

        String cfTemp = "";

        if (tempChoose.equals(CELSIUS_TEMP)) {

            // Create tempObject
            SoapObject tempObject = new SoapObject(NAMESPACE, METHOD_NAME_CTF);
            // Property which holds input parameters
            PropertyInfo tempPI = new PropertyInfo();
            // Set Name
            tempPI.setName("Celsius");
            // Set Value
            tempPI.setValue(temp);
            // Set dataType
            tempPI.setType(double.class);
            // Add the property to tempObject object
            tempObject.addProperty(tempPI);
            // Create envelope
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);
            // Set output SOAP object
            envelope.setOutputSoapObject(tempObject);
            envelope.dotNet = true;
            // Create HTTP call object
            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
            // Invole web service
            androidHttpTransport.call(SOAP_ACTION_CTF, envelope);
            // Get the response
            SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
            // Assign it to fahren variable
            cfTemp = "Fahrenheit Temp : " + result.toString() + "°";

        } else if (tempChoose.equals(FAHRENHEIT_TEMP)) {

            // Create tempObject
            SoapObject tempObject = new SoapObject(NAMESPACE, METHOD_NAME_FTC);
            // Property which holds input parameters
            PropertyInfo tempPI = new PropertyInfo();
            // Set Name
            tempPI.setName("Fahrenheit");
            // Set Value
            tempPI.setValue(temp);
            // Set dataType
            tempPI.setType(double.class);
            // Add the property to tempObject object
            tempObject.addProperty(tempPI);
            // Create envelope
            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                    SoapEnvelope.VER11);
            // Set output SOAP object
            envelope.setOutputSoapObject(tempObject);
            envelope.dotNet = true;
            // Create HTTP call object
            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
            // Invole web service
            androidHttpTransport.call(SOAP_ACTION_FTC, envelope);
            // Get the response
            SoapPrimitive result = (SoapPrimitive) envelope.getResponse();
            // Assign it to celsius variable
            cfTemp = "Celsius Temp : " + result.toString() + "°";
        }

        return cfTemp;
    }

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

        String tempInfo;

        @Override
        protected void onPreExecute() {

            progresslog = new ProgressDialog(TempConvertActivity.this, 1);
            progresslog.setMessage("Read Web Service...");
            progresslog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
            progresslog.show();
        }

        @Override
        protected String doInBackground(String... temp) {

            String resTemp = "";
            try {
                tempInfo = convertTemp(temp[0]);

            } catch (Throwable io) {
                resTemp = "error";
                tempInfo = io.getMessage();
            }
            return resTemp;
        }

        @Override
        protected void onPostExecute(String result) {
            String resultInfo = "";
            progresslog.dismiss();
            if (result.equals("")) {
                tempText.setText(tempInfo);
                resultInfo = "Convert finish";
            } else {
                resultInfo = tempInfo;
            }
            Toast.makeText(TempConvertActivity.this, resultInfo,
                    Toast.LENGTH_SHORT).show();
        }
    }
}

2. activity_temp_convert.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=".TempConvertActivity" >

    <EditText
        android:id="@+id/tempEt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Please input celsius temp"
        android:inputType="numberDecimal" >
    </EditText>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <TextView
            android:id="@+id/tempText"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_above="@+id/tempSwitch"
            android:layout_alignParentLeft="true"
            android:layout_marginBottom="25dp"
            android:text="Fahrenheit Temp : "
            android:textSize="20sp" />

        <Switch
            android:id="@+id/tempSwitch"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignBottom="@+id/cwsBtn"
            android:layout_alignParentLeft="true"
            android:layout_marginBottom="70dp"
            android:text="Temp type switch " />

        <Button
            android:id="@+id/cwsBtn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginTop="120dp"
            android:text="Call web service convert temp" />
    </RelativeLayout>

</LinearLayout>


3. AndroidManifest.xml(重點程式碼)
<uses-permission android:name="android.permission.INTERNET"/>

沒有留言: