Showing posts with label Ksoap2. Show all posts
Showing posts with label Ksoap2. Show all posts

Thursday, 10 April 2014

Parse JSON format data from SOAP Web service in Android

As JSON is so much preferred for android which is said to be easier to parse, faster and power saving lets try a simple example on JSON parsing. In this example we will learn how to parse JSON data from SOAP web service and use in our android program.

Check this post if your service is in XML format.

Lets take a simple JSON format data.
Example: 

[
  {
      "J_Name" : "yashwanth",
      "J_Id" : "04",
      "J_Place":"Hosur",
      "J_Phone":"9876543210"
  }
]




Step 1 : Create a new project in Eclipse IDE File ⇒ New ⇒ Android Application Project and fill all the required details.

Step 2 : In your layout file place some text fields and align it as required.


Step 3 : Add Internet Permission in your project manifest file .

AndroidManifest.xml : 


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="www.andygeeks.blogspot.com"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<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="www.andygeeks.blogspot.com.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>

Step 4 : Include the KSOAP2 jar file in to your project. Right click project ⇒ Properties ⇒ Java build path ⇒ Libraries Tab ⇒ Add External Jars ⇒ browse and add KSOAP2 Jar file and gson Jar file.

Step 5 : Now call the web service and get details with asynctask. Paste this below code in your MainActivity class file.

MainActivity.java :


package www.andygeeks.blogspot.com;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import org.json.JSONArray;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
   
boolean timeoutexcep=false,httpexcep=false,genexcep=false;
   
private static final String TAG_NAME = "J_Name";
private static final String TAG_ID = "J_Id";
private static final String TAG_PLACE = "J_Place";
private static final String TAG_MOBILE = "J_Phone";
   
public static String dist="Krishnagiri",type="P",no="50";
String Name,Id,Place,Phone;
   
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new pay().execute();
}

class pay extends AsyncTask<Void, Void, Void> {

private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

@Override
protected void onPreExecute() {
this.dialog.setMessage("Loading data");
this.dialog.show();
}

@Override
protected Void doInBackground(Void... unused) {

final String NAMESPACE = "http://tempuri.org/";
final String URL = "http://www.xxxxxx.com/xxxx/xxx.asmx";
final String SOAP_ACTION = "http://tempuri.org/xxxxx";
final String METHOD_NAME = "xxxxx";

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

request.addProperty("sDistrict", dist);
request.addProperty("sTaxType", type);
request.addProperty("sTaxNo", no);

SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;

envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;

try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive response = (SoapPrimitive) envelope.getResponse();

String responseJSON=response.toString();
JSONArray jarray =new JSONArray(responseJSON);

Name=jarray.getJSONObject(0).getString(TAG_NAME);
Id=jarray.getJSONObject(0).getString(TAG_ID);
Place=jarray.getJSONObject(0).getString(TAG_PLACE);
Phone=jarray.getJSONObject(0).getString(TAG_MOBILE);

System.out.println(request);
System.out.println(responseJSON);

}
catch(SocketTimeoutException e){
timeoutexcep=true;
e.printStackTrace();
}
catch(UnknownHostException e){
httpexcep=true;
e.printStackTrace();
}
catch (Exception e) {
genexcep=true;
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}
if(timeoutexcep){
Toast.makeText(MainActivity.this, "Unable to connect to server, Please try again later",Toast.LENGTH_LONG).show();
}
else if(httpexcep){
Toast.makeText(MainActivity.this, "Please check your Internet connection",Toast.LENGTH_LONG).show();
}
else if(genexcep){
Toast.makeText(MainActivity.this, "Please try later",Toast.LENGTH_LONG).show();
}

else{
tableview();
}
timeoutexcep=false;httpexcep=false;genexcep=false;
}
}

public void tableview(){
try{
TextView name = (TextView)findViewById(R.id.textView5);
name.setText(Name);

TextView door = (TextView)findViewById(R.id.textView6);
door.setText(Id);

TextView ward = (TextView)findViewById(R.id.textView7);
ward.setText(Place);

TextView mobile = (TextView)findViewById(R.id.textView8);
mobile.setText(Phone);
}
catch(Exception e){
}
}
   
@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;
}
}

Friday, 14 February 2014

How to get data from SOAP web service as object contains array of values

Here we shall see how to get data from SOAP web service when the response is returned as an object in XML format. When the response is object you have to create a bean class and retrieve the data. When you get single values for each variable use this post.

And when you get single value for variables (Eg. Name= yashwanth; Age=25; place=Hosur) Check this link.









Step 1 : Create a new project in Eclipse IDE File ⇒ New ⇒ Android Application Project and fill all the required details.

Step 2 : In your layout file place some text fields and align is as required.

Activity_main.xml:


<?xml version="1.0" encoding="utf-8"?>
<HorizontalScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >

<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical" >

<TableLayout
android:id="@+id/tl1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >

<TableRow
android:id="@+id/tabrow1"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:id="@+id/textView1"
android:layout_width="0dp"
android:layout_weight="1"
android:textAlignment="center"
android:text="@string/Id"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#f2c21b" />

<TextView
android:id="@+id/textView2"
android:layout_width="0dp"
android:layout_weight="1"
android:text="@string/Name"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#f2c21b" />

<TextView
android:id="@+id/textView3"
android:layout_width="0dp"
android:layout_weight="1"
android:text="@string/Place"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#f2c21b" />

<TextView
android:id="@+id/textView4"
android:layout_width="0dp"
android:layout_weight="1"
android:text="@string/District"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textColor="#f2c21b" />

</TableRow>
</TableLayout>

<ScrollView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="-100dp"
android:scrollbars="vertical" >

<TableLayout
android:id="@+id/tl"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
</TableLayout>
</ScrollView>
</LinearLayout>
</HorizontalScrollView>

Step 3 : Add Internet Permission in your project manifest file .

AndroidManifest.xml :


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exam.webservice2"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<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.exam.webservice2.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>

Step 4 : Include the KSOAP2 jar file in to your project. Right click project ⇒ Properties ⇒ Java build path ⇒ Libraries Tab ⇒ Add External Jars ⇒ browse and add KSOAP2  jar file you can find it Here.

Step 5 : Now crate a new class in your existing package and name that class as Bean. Now paste the below code in your bean class file.

Bean.java :


package com.exam.webservice2;

import java.util.Hashtable;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;

public class Bean implements KvmSerializable
{
public String Id;
public String Name;
public String Place;
public String District;

public Bean(){}

public Bean(String Id,String Name, String Place,String District)
{
this.Id = Id;
this.Name=Name;
this.Place=Place;
this.District=District;
}

public Object getProperty(int arg0) {

switch(arg0)
{
case 0:
return Id;
case 1:
return Name;
case 2:
return Place;
case 3:
return District;
}
return null;
}

public int getPropertyCount() {
return 4;
}

@SuppressWarnings("rawtypes")
public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
switch(index)
{
case 0:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Id";
break;
case 1:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Name";
break;
case 2:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Place";
break;
case 3:
info.type = PropertyInfo.STRING_CLASS;
info.name = "District";
break;

default:
break;
}
}

public void setProperty(int index, Object value) {
switch(index)
{
case 0:
Id = value.toString();
break;
case 1:
Name = value.toString();
break;
case 2:
Place = value.toString();
break;
case 3:
District = value.toString();
break;

default:
break;
}
}
}

Step 6 : Now call the web service and get details with asynctask. Paste this below code in your MainActivity class file.

MainActivity.java :


package com.exam.webservice2;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.util.Arrays;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
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.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TableRow.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

String typ="P",uu="500229";
boolean timeoutexcep=false,httpexcep=false,generalexcep=false;
Bean[] personList2;
TableLayout ll;
String[] Id,Name,District,Place;
int i;

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

new propdetail().execute();
}

class propdetail extends AsyncTask<Void, Void, Void> {

private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

@Override
protected void onPreExecute() {
this.dialog.setMessage("Loading data");
this.dialog.show();
}

@Override
protected Void doInBackground(Void... unused) {

final String NAMESPACE = "http://tempuri.org/";
final String URL = "http://192.162.1.10/Test/Service.asmx";
final String SOAP_ACTION = "http://tempuri.org/GetDetails";
final String METHOD_NAME = "GetDetails";

SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

request.addProperty("sTaxType", typ);
request.addProperty("sUserId", uu);

Bean C = new Bean();
PropertyInfo pi = new PropertyInfo();
pi.setName("Bean");
pi.setValue(C);
pi.setType(C.getClass());
request.addProperty(pi);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
envelope.addMapping(NAMESPACE, "Bean", new Bean().getClass());
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;

try {
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapObject response = (SoapObject) envelope.getResponse();

Log.i("myApp", request.toString());
System.out.println("check dddddddddddddd" + response);

envelope.addMapping(NAMESPACE, "Panchayat",new Bean().getClass());
androidHttpTransport.call(SOAP_ACTION, envelope);
personList2 = new Bean[response.getPropertyCount()];

for (int j = 0; j < personList2.length; j++) {
SoapObject so = (SoapObject) response.getProperty(j);
Bean person2 = new Bean();
person2.Id = so.getProperty(0).toString();
person2.Name= so.getPropertyAsString(1).toString();
person2.Place=so.getPropertyAsString(6).toString();
person2.District=so.getPropertyAsString(7).toString();
personList2[j] = person2;
}

Id = new String[personList2.length];
Name = new String[personList2.length];
Place = new String[personList2.length];
District = new String[personList2.length];

for (int i = 0; i < personList2.length; i++)
{
Place[i] = Arrays.asList(personList2[i].Id).toString();
Id[i] = Arrays.asList(personList2[i].Name).toString();
Name[i] = Arrays.asList(personList2[i].Place).toString();
District[i] = Arrays.asList(personList2[i].District).toString();

System.out.println(Id[i]);
System.out.println(Name[i]);
System.out.println(District[i]);
System.out.println(Place[i]);
}
}
catch(SocketTimeoutException e){
timeoutexcep=true;
e.printStackTrace();
}
catch(ConnectException e){
httpexcep=true;
e.printStackTrace();
}
catch (Exception e) {
generalexcep=true;
e.printStackTrace();
}
return null;
}

@Override
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}


if(timeoutexcep){
Toast.makeText(MainActivity.this, "Unable to connect to server, Please try again later",Toast.LENGTH_LONG).show();
}
else if(httpexcep){
Toast.makeText(MainActivity.this, "Please check your Internet connection",Toast.LENGTH_LONG).show();
}
else if(generalexcep){
Toast.makeText(MainActivity.this, "Please try later",Toast.LENGTH_LONG).show();
}
else {
tableview();
}
timeoutexcep=false;httpexcep=false;generalexcep=false;
}
}
public void tableview(){

ll = (TableLayout) findViewById(R.id.tl);
for (i = 0; i < personList2.length; i++)
{
final TableRow tr = new TableRow(this);
LayoutParams lp = new LayoutParams(150,LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);

tr.setId(i);

tr.setLayoutParams(lp);
lp.setMargins(0, 20, 0, 0);

final TextView tvLeft = new TextView(this);
tvLeft.setLayoutParams(lp);
tvLeft.setText(Id[i]);

final TextView tvCenter = new TextView(this);
tvCenter.setLayoutParams(lp);
tvCenter.setText(Name[i]);

final TextView tvRight = new TextView(this);
tvRight.setLayoutParams(lp);
tvRight.setText(Place[i]);

final TextView tvend = new TextView(this);
tvend.setLayoutParams(lp);
tvend.setText(District[i]);

tr.addView(tvLeft);
tr.addView(tvCenter);
tr.addView(tvRight);
tr.addView(tvend);

ll.addView(tr, new TableLayout.LayoutParams (LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
}

@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;
}
}

Thursday, 13 February 2014

How to get data from SOAP webservice object in Android

Here we shall see how to get data from SOAP web service when the response is returned as an object in XML format. When the response is object you have to create a bean class and retrieve the data. When you get single values for each variable use this post. we will also see how to parse XML data from .NET web service soap object in android.

Check this post if your service is in JSON format.

And when you get many values for single variable(Eg. Name= yashwanth, Prabhakar, Abdul, John; Id=1,2,3,4; Place = Hosur, bang, trichy, chennai ) check this post.







Step 1: Create a new project in Eclipse IDE File ⇒ New ⇒ Android Application Project and fill all the required details.

Step 2: In your layout file place some text fields and align is as required.

Activity_main.xml:


<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_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="97dp"
android:text="Name"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView4"
android:layout_below="@+id/textView4"
android:layout_marginTop="24dp"
android:text="Phone"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView1"
android:layout_below="@+id/textView1"
android:layout_marginTop="26dp"
android:text="Place"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/textView4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="@+id/textView2"
android:layout_below="@+id/textView2"
android:layout_marginTop="20dp"
android:text="Age"
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView1"
android:layout_alignBottom="@+id/textView1"
android:layout_centerHorizontal="true"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/phone"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView3"
android:layout_alignBottom="@+id/textView3"
android:layout_centerHorizontal="true"
android:text=""

android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/age"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/textView2"
android:layout_alignBottom="@+id/textView2"
android:layout_alignLeft="@+id/name"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
android:id="@+id/palce"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="@+id/textView3"
android:layout_alignLeft="@+id/phone"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />

</RelativeLayout>

Step 3: Add Internet Permission in your project manifest file .

AndroidManifest.xml :


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.exam.webservice1"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="19" />
<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.exam.webservice1.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>

Step 4: Include the KSOAP2 jar file in to your project. Right click project ⇒ Properties ⇒ Java build path ⇒ Libraries Tab ⇒ Add External Jars ⇒ browse and add KSOAP2 Jar file.

Step 5: Now crate a new class in your existing package and name that class as Bean. Now paste the below code in your bean class file.

Bean.java :


package com.exam.webservice1;

import java.util.Hashtable;
import org.ksoap2.serialization.KvmSerializable;
import org.ksoap2.serialization.PropertyInfo;


public class Bean implements KvmSerializable
{
public String Name;
public String Place;
public String Age;
public String Phone;

public Bean(){}

public Bean( String Name,String Place,String Age,String Phone)
{
this.Name=Name;
this.Place=Place;
this.Age=Age;
this.Phone=Phone;
}

public Object getProperty(int arg0) {
switch(arg0)
{
case 0:
return Name;
case 1:
return Place;
case 2:
return Age;
case 3:
return Phone;
}
return null;
}

public int getPropertyCount() {
return 4;
}

@SuppressWarnings("rawtypes")
public void getPropertyInfo(int index, Hashtable arg1, PropertyInfo info) {
switch(index)
{
case 0:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Name";
break;
case 1:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Place";
break;
case 2:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Age";
break;
case 3:
info.type = PropertyInfo.STRING_CLASS;
info.name = "Phone";
break;
default:
break;
}
}

public void setProperty(int index, Object value) {
switch(index)
{
case 0:
Name = value.toString();
break;
case 1:
Place = value.toString();
break;
case 2:
Age = value.toString();
break;
case 3:
Phone = value.toString();
break;
default:
break;
}
}
}

Step 6: Now call the web service and get details with asynctask. Paste this below code in your MainActivity class file.

MainActivity.java :


package com.exam.webservice1;

import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.PropertyInfo;
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.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

boolean timeoutexcep=false,httpexcep=false,generalexcep=false;
String UserName="yuki",Id="y475";

String name,place,age,phone;

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

new Persondetails().execute();
}

@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;
}

class Persondetails extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(MainActivity.this);

@Override
protected void onPreExecute() {
this.dialog.setMessage("Loading data");
this.dialog.show();
}


@Override
protected Void doInBackground(Void... unused) {

final String NAMESPACE = "http://tempuri.org/";
final String URL = "http://192.168.1.1/Java/Service1.asmx";
final String SOAP_ACTION = "http://tempuri.org/CheckDetails";
final String METHOD_NAME = "CheckDetails";

SoapObject request2 = new SoapObject(NAMESPACE, METHOD_NAME);

request2.addProperty("sUserName", UserName);
request2.addProperty("sId", Id);


Bean C = new Bean();
PropertyInfo pi = new PropertyInfo();
pi.setName("Bean");
pi.setValue(C);
pi.setType(C.getClass());
request2.addProperty(pi);
SoapSerializationEnvelope envelope2 = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope2.dotNet = true;
envelope2.setOutputSoapObject(request2);
envelope2.addMapping(NAMESPACE, "Bean", new Bean().getClass());
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;

try {
androidHttpTransport.call(SOAP_ACTION, envelope2);
SoapObject response2 = (SoapObject) envelope2.getResponse();


System.out.println("check Request" + request2);
System.out.println("check response" + response2);

envelope2.addMapping(NAMESPACE, "Panchayat",new Bean().getClass());
androidHttpTransport.call(SOAP_ACTION, envelope2);
Bean[] personobj = new Bean[response2.getPropertyCount()];
Bean beanobj = new Bean();

for (int j = 0; j < personobj.length; j++) {
SoapObject pii = (SoapObject) response2.getProperty(j);
beanobj.Name = pii.getProperty(1).toString();
beanobj.Place = pii.getProperty(2).toString();
beanobj.Age = pii.getProperty(3).toString();
beanobj.Phone = pii.getProperty(4).toString();

personobj[j] = beanobj;
}

name=beanobj.Name;
age=beanobj.Place;
place=beanobj.Age;
phone=beanobj.Phone;

}
catch(SocketTimeoutException e){
timeoutexcep=true;
e.printStackTrace();
}
catch(ConnectException e){
httpexcep=true;
e.printStackTrace();
}
catch (Exception e) {
generalexcep=true;
e.printStackTrace();
}
return null;

}
@Override
protected void onPostExecute(Void result) {
if (this.dialog.isShowing()) {
this.dialog.dismiss();
}

if(timeoutexcep){
Toast.makeText(MainActivity.this, "Unable to connect to server, Please try again later",Toast.LENGTH_LONG).show();
}
else if(httpexcep){
Toast.makeText(MainActivity.this, "Please check your Internet connection",Toast.LENGTH_LONG).show();
}
else if(generalexcep){
Toast.makeText(MainActivity.this, "Please try later",Toast.LENGTH_LONG).show();
}

else {
display();
}
timeoutexcep=false;httpexcep=false;generalexcep=false;
}

private void display() {

TextView t1=(TextView)findViewById(R.id.name);
t1.setText(name);
TextView t2=(TextView)findViewById(R.id.palce);
t2.setText(place);
TextView t3=(TextView)findViewById(R.id.age);
t3.setText(age);
TextView t4=(TextView)findViewById(R.id.phone);
t4.setText(phone);
}
}
}



Thursday, 31 October 2013

Simple Android program using .Net web service and Ksoap2


I have given very simple program that uses .Net web service and we display that data in our android program in a text field.


Your .Net web service should return a string like this:


[WebMethod]

public string Test()
{
string sValue = string.Empty;
try
{
sValue = "This is from web service, Yashwanth";
}
catch (Exception ex)
{
sValue = ex.Message.ToString();
}
finally
{
}
return sValue;
}



Create a new android project using eclipse and in your MainActivity class paste the following code. Change the Package name and Activity name of yours.



And your android program:

package com.test.webservice;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

public class MainActivity extends Activity

{
private static final String SOAP_ACTION = "http://tempuri.org/Test";
private static final String METHOD_NAME = "Test";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://192.168.1.40/Test/Service.asmx";

TextView tv;

@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv=(TextView)findViewById(R.id.textView1);
call();
}
public void call()
{
try {
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
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();
tv.setText(response.toString());
}

catch (Exception e) {
Toast.makeText(MainActivity.this,"Error - " +e.getMessage()
.toString(),Toast.LENGTH_LONG).show();
}}

@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;
}
}

Your activity_main xml should look like this:

<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"
tools:context=".MainActivity" >

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true" />
</RelativeLayout>

Your AndroidManifest.xml file:

In AndroidManifest.xml in permission tab add Uses Permission ⇒
Name = android.permission.INTERNET

<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.examp.web"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<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.examp.web.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>


Output: