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

38 comments:

  1. im getting error please try later ...

    im getting a screen with 3 "textview" label

    ReplyDelete
    Replies
    1. Its a general exception. Post your error that display's on your logcat

      Delete
    2. textview because you prolly set text in your layout file

      Delete
  2. i am getting error on SoapPrimitive.
    error is:
    java.lang.ClassCastException: java.lang.String cannot be cast to org.ksoap2.serialization.SoapPrimitive

    ReplyDelete
  3. [{"UserId":332,"Name":"Jaydeep Patel"},{"UserId":330,"Name":"new patient"},{"UserId":334,"Name":"Sanket Narola"}]
    it want this data to display in listview how can i display this

    ReplyDelete
  4. Existing without the answers to the difficulties you’ve sorted out through this guide is a critical case, as well as the kind which could have badly affected my entire career if I had not discovered your website.
    Digital Marketing Training in Chennai

    Aws Training in Chennai

    Selenium Training in Chennai

    ReplyDelete
  5. After seeing your article I want to say that the presentation is very good and also a well-written article with some very good information which is very useful for the readers....thanks for sharing it and do share more posts like this.
    python training institute in chennai
    python training in Bangalore
    python training institute in chennai

    ReplyDelete
  6. Really very nice blog information for this one and more technical skills are improve,i like that kind of post.

    devops online training

    aws online training

    data science with python online training

    data science online training

    rpa online training

    ReplyDelete
  7. You might comment on the order system of the blog. You should chat it's splendid. Your blog audit would swell up your visitors. I was very pleased to find this site.I wanted to thank you for this great read!!
    www.excelr.com/digital-marketing-training
    digital marketing course

    ReplyDelete
  8. Attend The Python Training in Hyderabad From ExcelR. Practical Python Training Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Python Training in Hyderabad.
    python training in bangalore

    ReplyDelete
  9. ExcelR offers data science training in hyderabad , the most comprehensive Data Science course in the market, covering the complete Data Science lifecycle concepts from Data Collection, Data Extraction, Data Cleansing, Data Exploration, Data Transformation, Feature Engineering, Data Integration, Data Mining, building Prediction models.

    ReplyDelete
  10. Attend The Course in Data Analytics From ExcelR. Practical Course in Data Analytics Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Course in Data Analytics.
    ExcelR Course in Data Analytics

    ReplyDelete
  11. Attend The Data Science Courses Bangalore From ExcelR. Practical Data Science Courses Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Data Science Courses Bangalore.
    ExcelR Data Science Courses Bangalore
    Data Science Interview Questions
    ExcelR Business Analytics Course
    ExcelR Data Analytics Courses

    ReplyDelete
  12. After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article.

    Simple Linear Regression

    Correlation vs Covariance

    ReplyDelete
  13. "I am looking for and I love to post a comment thatExcelR Online data science training
    ""The content of your post is awesome"" Great work!"

    ReplyDelete
  14. ExcelR provides Data analyst course. It is a great platform for those who want to learn and become a Data Analyst. Students are tutored by professionals who have a degree in a particular topic. It is a great opportunity to learn and grow.

    Data analyst course

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. This comment has been removed by the author.

    ReplyDelete
  17. This comment has been removed by the author.

    ReplyDelete
  18. This comment has been removed by the author.

    ReplyDelete
  19. with Placement | 3RI Technologies
    data Analytics courses in pune
    3RI Technologies is the leading institution offering instructor-data analytics courses in pune Fresh graduates and working professionals can also enroll in it. 3RI Technologies offers well-managed data analytics courses in pune
    data analytics Courses in Pune

    ReplyDelete
  20. This post is so interactive and informative.keep update more information...
    DevOps course in Tambaram
    DevOps Training in Chennai

    ReplyDelete
  21. Unleash your potential and expand your capabilities with the Data Science Certification Course. Your transformation of career begins here. Become proficient in mastering the advanced skills.
    data scientist course

    ReplyDelete
  22. Devops Training Institute in KPHB

    ReplyDelete
  23. With a distinctive curriculum and methodology, our Data Science certification programme enables you to secure a position in prestigious businesses. Use all the advantages to succeed as a champion.data science course institute in nagpur

    ReplyDelete
  24. SkillUp Online provides Python for Data Science Course to excel your R programming skills to the next level.

    ReplyDelete