Skip to main content

Android web service access using Async Task



Android web service access using Async Task
In Android we can use Async Tasks to perform background activities without interrupting main gui thread. So it is ideal for the tasks like web service accessing in Android. In this post I'm going to demonstrate a very simple application which uses Async Task to access soap based web service. Here I access .NET web service Currency Converter provided by http://www.webservicex.net/

To create this application you need to have ksoap2 libaray. (You can download latest version of ksoap2 from here : 
http://code.google.com/p/ksoap2-android/wiki/HowToUse?tm=2 click the url under "with a direct download url of ").


Here is the quick demo of the application.



https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEhAU6Wn-rzr8grL9a5xph3nBlgPmjF2LMwkV7T069lcOM9dRPnUzEiD7maYsQjBxKQR1ECdEASY0kKEdoOTH-91NTUqvOgOYhNlV24GJiNvbTf9UfzZemQxkdoqORSwbiUAGiTbwQHGiW-I/s320/android+web+service+access+using+async+task.png

Code for the main activity:


In line 68 I have set "envelope.dotNet = true;" because I'm accessing .NET web service. You can comment that line if you are accessing other web service.
?




























































































package com.soap.client;

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.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
 private TextView textView;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textView = (TextView) findViewById(R.id.textView1);
  this.accessWebService(textView);
 }

 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  // Inflate the menu; this adds items to the action bar if it is present.
  getMenuInflater().inflate(R.menu.main, menu);
  return true;
 }
  
 //starting asynchronus task
 private class SoapAccessTask extends AsyncTask<String, Void, String> {
      
     @Override
     protected void onPreExecute() {
          //if you want, start progress dialog here
     }
          
     @Override
     protected String doInBackground(String... urls) {
         String webResponse = "";
        try{
          final String NAMESPACE = "http://www.webserviceX.NET/";
          final String URL = "http://www.webservicex.net/CurrencyConvertor.asmx";
          final String SOAP_ACTION = "http://www.webserviceX.NET/ConversionRate";
          final String METHOD_NAME = "ConversionRate";
           
          SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
          PropertyInfo fromProp =new PropertyInfo();
          fromProp.setName("FromCurrency");
          //gets the first element from urls array
          fromProp.setValue(urls[0]);
          fromProp.setType(String.class);
          request.addProperty(fromProp);
             
          PropertyInfo toProp =new PropertyInfo();
          toProp.setName("ToCurrency");
          //second element of the urls array
          toProp.setValue(urls[1]);
          toProp.setType(String.class);
          request.addProperty(toProp);
            
          SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
          envelope.dotNet = true;
          envelope.setOutputSoapObject(request);
          HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
           
          androidHttpTransport.call(SOAP_ACTION, envelope);
          SoapPrimitive response = (SoapPrimitive)envelope.getResponse();
          webResponse = response.toString();
       }
       catch(Exception e){
          Toast.makeText(getApplicationContext(),"Cannot access the web service"+e.toString(), Toast.LENGTH_LONG).show();
        }
         return webResponse;
    }
   
    @Override
    protected void onPostExecute(String result) {
            //if you started progress dialog dismiss it here
            textView.setText(result);
            Toast.makeText(getApplicationContext(),"Completed...", Toast.LENGTH_LONG).show();
         }
     }
  
   public void accessWebService(View view) {
   SoapAccessTask task = new SoapAccessTask();
      //passes values for the urls string array
      task.execute(new String[] { "USD","LKR"});
     } 
}
Code for the layout





















<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="89dp"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

You have to add INTERNET permission to AndroidManifest.xml
























<?xml version="1.0" encoding="utf-8"?>
    package="com.soap.client"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="17"
        android:targetSdkVersion="17" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.soap.client.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Comments

Popular posts from this blog

Volley for client and server interaction (Android)

Volley provides client and server interaction with QUEUE basis, each and every request process separately, we can cancel our request from QUEUE. HERE is a code sample for Volley with json request format. GenerateRequest.java -------------------------------------------------------------------- package com.entrata.maintenance.network_communication.networkutils; import android.content.Context; import com.android.volley.AuthFailureError; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.entrata.maintenance.application.ERPUserDefaults; import com.entrata.maintenance.network_communication.networkconstant.NetworkConstant; import com.entrata.maintenance.network_communication.networkexception.Error; import com.entrata.maintenance.network_communication.networkutil.SubdomainChange; import com.entrata.maintenance.utils.Logger; import com.google.gson.Gson; import org.json.JSONException; import org.js...
Java Code Examples for javax.net.ssl.HttpsURLConnection The following code examples are extracted from open source projects. You can click to vote up the examples you like. Your votes will be used in an intelligent system to get more and better code examples. Thanks for your votes! Code Example 1:   9  From project ADFS , under directory /adfs-hdfs-project/adfs-hdfs/src/main/java/org/apache/hadoop/hdfs/ . Source HsftpFileSystem.java @Override protected HttpURLConnection openConnection ( String path , String query ) throws IOException { query = addDelegationTokenParam ( query ); final URL url = new URL ( "https" , nnAddr . getHostName (), nnAddr . getPort (), path + '?' + query ); HttpsURLConnection conn =( HttpsURLConnection ) url . openConnection (); conn . setHostnameVerifier ( new DummyHostnameVerifier ()); return ( HttpURLConnection ) conn ; } Code Example 2:  ...

Improving Layout Performance

Improving Layout Performance Layouts are a key part of Android applications that directly affect the user experience. If implemented poorly, your layout can lead to a memory hungry application with slow UIs. The Android SDK includes tools to help you identify problems in your layout performance, which when combined the lessons here, you will be able to implement smooth scrolling interfaces with a minimum memory footprint. Lessons Optimizing Layout Hierarchies In the same way a complex web page can slow down load time, your layout hierarchy if too complex can also cause performance problems. This lesson shows how you can use SDK tools to inspect your layout and discover performance bottlenecks. Re-using Layouts with <include/> If your application UI repeats certain layout constructs in multiple places, this lesson shows you how to create efficient, re-usable layout constructs, then include them in the appropriate UI layouts. Loading Views On Demand Be...