Tag Archives: webservice

Android – Simple XML DOM Parser Example for Reading Response From InputStream


Hi,

I am trying to use simple XML DOM Parser for my HTTP response.

Basically I am calling .Net webservice and I need to parse response.

Let me also cover calling the .Net webservice.

Webservice can be called/consumed by may way.
For Example:

Use SOAP call, HTTP Get method, HTTP Post method and many more..

I have one Web service method with Post call structure:

POST /api.asmx/validateCredentials HTTP/1.1
Host: api.mywebsite.com
Content-Type: application/x-www-form-urlencoded
Content-Length: length

username=string&password=string

Now I want to call it from Android HTTP Post method.
I will also need BasicNameValue pair for sending data to web service URL.

I’ll do it like:

try {
	HttpClient httpClient = new DefaultHttpClient();
	HttpContext localContext = new BasicHttpContext();
	HttpPost httpPost = new HttpPost("http://api.mywebsite.com/api.asmx/validateCredentials");

	List<NameValuePair> nvps = new ArrayList<NameValuePair>();

	nvps.add(new BasicNameValuePair("username", username));
	nvps.add(new BasicNameValuePair("password", password));

	httpPost.setEntity(new UrlEncodedFormEntity(nvps));

	HttpResponse response = httpClient.execute(httpPost, localContext);

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

Now First of all I wanted my response as String.

So I use Buffer reader to read the data from response object.

BufferedReader reader = new BufferedReader(new InputStreamReader(
		response.getEntity().getContent(), "UTF-8"));
StringBuffer responseString = new StringBuffer("");
String line;
while ((line = reader.readLine()) != null) {
	responseString.append(line);
}
System.out.println(responseString.toString());

Now I can see the response in LogCat.
I get the XML response (in String) as follow:

<?xml version="1.0" encoding="utf-8"?>
<returnMessage xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://api.myserver.com/">
	<responseCode>S000</responseCode>
	<message>User Authenticated</message>
	<extendedMessage>
		The user's credentials were valid and is authorized to execute this transaction.
	</extendedMessage>
	<userno xsi:type="xsd:double">211</userno>
</returnMessage>

Here you can see some tags and actually we need those values!!

So I can now use this “String” object to parse the XML.

To parse the XML we have several methods like SAX parser, DOM parser XML pool parser etc.

I heard that SAX parser is best, I had also used that one, But here I will go with Simple DOM parser.

So Instead of getting the response in String as above, I can directly use InputStream for DOM parser.

InputStream in = response.getEntity().getContent();

DocumentBuilder builder = DocumentBuilderFactory.newInstance()
		.newDocumentBuilder();
Document doc = builder.parse(in);
String responseCode = "";
String extendedMessage = "";
if (doc != null) {
	NodeList nl = doc.getElementsByTagName("responseCode");
	if (nl.getLength() > 0) {
		Node node = nl.item(0);
		responseCode = node.getTextContent();
	}
	nl = doc.getElementsByTagName("extendedMessage");
	if (nl.getLength() > 0) {
		Node node = nl.item(0);
		extendedMessage = node.getTextContent();
	}
}
System.out.println(responseCode + " " + extendedMessage);

I hope this post can help some one who wants to get started with Android in just 10 minutes!

Calling a FedEx Rate Service from Classic ASP with SOAP call


Hi Friends,

Last month I worked in Classic ASP. I had to prepare a Delivery Calendar.

I consumed a FedEx web service for Rate request.

It can also return delivery commitment details like Delivery Date, Time, date etc.

Basically what I need is to call a web service using SOAP call.

May people find difficulty in Classic ASP, as FexEx is not giving sample code for consuming their web service.

So I decided to post at least on web service call, so that you guys can have idea about how to consume FedEx Web service in Classic ASP.

FedExCall.asp

<% option explicit %>
<!--#include file="FedexAccountInfo.asp"-->
<%
    Dim subscriberzip
    Dim subscribercountry
    Dim ShipmentDate
    Dim xmlReq
    Dim objhttp
    Dim outstr
    Dim NodeList

    subscriberzip = Request.QueryString("zip")
    subscribercountry = "US"
    ShipmentDate = Request.QueryString("date")

    xmlReq = "<?xml version=""1.0"" encoding=""UTF-8""?>" &_
    "<soapenv:Envelope xmlns:soapenv=""http://schemas.xmlsoap.org/soap/envelope/"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"">" &_
    "<soapenv:Body>" &_
    "<RateRequest xmlns=""http://fedex.com/ws/rate/v9"">" &_
    "<WebAuthenticationDetail>" &_
    "<UserCredential>" &_
    "<Key>" & FedExkey & "</Key>" &_
    "<Password>" & FedExPassword & "</Password>" &_
    "</UserCredential>" &_
    "</WebAuthenticationDetail>" &_
    "<ClientDetail>" &_
    "<AccountNumber>" & FedExAccountNumber & "</AccountNumber>" &_
    "<MeterNumber>" & FedExMeterNumber & "</MeterNumber>" &_
    "</ClientDetail>" &_
    "<TransactionDetail>" &_
    "<CustomerTransactionId>TEST</CustomerTransactionId>" &_
    "</TransactionDetail>" &_
    "<Version>" &_
    "<ServiceId>crs</ServiceId>" &_
    "<Major>9</Major>" &_
    "<Intermediate>0</Intermediate>" &_
    "<Minor>0</Minor>" &_
    "</Version>" &_
    "<ReturnTransitAndCommit>1</ReturnTransitAndCommit>" &_
    "<CarrierCodes>FDXE</CarrierCodes>" &_
    "<VariableOptions>SATURDAY_DELIVERY</VariableOptions>" &_
    "<RequestedShipment>" &_
    "<ShipTimestamp>" & ShipmentDate & "T09:00:00-00:00</ShipTimestamp>" &_
    "<DropoffType>REGULAR_PICKUP</DropoffType>" &_
    "<PackagingType>YOUR_PACKAGING</PackagingType>" &_
    "<Shipper>" &_
    "<Address>" &_
    "<PostalCode>96790</PostalCode>" &_
    "<CountryCode>US</CountryCode>" &_
    "</Address>" &_
    "</Shipper>" &_
    "<Recipient>" &_
    "<Address>" &_
    "<PostalCode>" & subscriberzip & "</PostalCode>" &_
    "<CountryCode>US</CountryCode>" &_
    "</Address>" &_
    "</Recipient>" &_
    "<ShippingChargesPayment>" &_
    "<PaymentType>SENDER</PaymentType>" &_
    "<Payor>" &_
    "<AccountNumber>" & FedExAccountNumber & "</AccountNumber>" &_
    "<CountryCode>US</CountryCode>" &_
    "</Payor>" &_
    "</ShippingChargesPayment>" &_
    "<RateRequestTypes>LIST</RateRequestTypes>" &_
    "<PackageCount>1</PackageCount>" &_
    "<PackageDetail>INDIVIDUAL_PACKAGES</PackageDetail>" &_
    "<RequestedPackageLineItems>" &_
    "<SequenceNumber>1</SequenceNumber>" &_
    "<Weight>" &_
    "<Units>LB</Units>" &_
    "<Value>10.0</Value>" &_
    "</Weight>" &_
    "</RequestedPackageLineItems>" &_
    "</RequestedShipment>" &_
    "</RateRequest>" &_
    "</soapenv:Body>" &_
    "</soapenv:Envelope>"

    set objHttp = Server.createobject("Msxml2.ServerXMLHTTP")

    'For live
    objHttp.open "POST", https://gateway.fedex.com:443/web-services/rate, false

    'For test
    'objHttp.open "POST", https://gatewaybeta.fedex.com:443/web-services/rate, false

    OBJHTTP.setRequestHeader "Referer", "Your Company name"
    OBJHTTP.setRequestHeader "Host", "wsbeta.fedex.com"
    OBJHTTP.setRequestHeader "Accept", "image/gif, image/jpeg,image/pjpeg, text/plain, text/html, */*"
    OBJHTTP.setRequestHeader "Content-Type", "image/gif"
    OBJHTTP.setRequestHeader "Content-Length", cstr(len(xmlReq))

    objHttp.Send xmlReq

    outstr = objHttp.responseText

    dim objDoc, i, j, status
    Set objDoc = CreateObject("Microsoft.XMLDOM")
    objDoc.async = False
    objDoc.LoadXml(outstr)

'    Response.Write objDoc.getElementsByTagName("v9:HighestSeverity")(0).text

    Set NodeList = objDoc.getElementsByTagName("v9:RateReplyDetails")

    for i=0 to (NodeList.length-1)
'        for j=0 to (NodeList(0).childNodes.length-1)
'            if Trim(NodeList(i).childNodes(j).nodename) = "v9:ServiceType" then
'                Response.write "ServiceType: " & Trim(NodeList(i).childNodes(j).text) & "<br/>"
'            elseif Trim(NodeList(i).childNodes(j).nodename) = "v9:DeliveryDayOfWeek" then
'                Response.write "Day: " & Trim(NodeList(i).childNodes(j).text) & "<br/>"
'            elseif Trim(NodeList(i).childNodes(j).nodename) = "v9:DeliveryTimestamp" then
'                Response.write "Date: " & left(Trim(NodeList(i).childNodes(j).text), 10) & "<br/>"
'                Response.write "Time: " & right(Trim(NodeList(i).childNodes(j).text), 8) & "<br/>"
'            elseif Trim(NodeList(i).childNodes(j).nodename) = "v9:DestinationServiceArea" then
'                Response.write "Area: " & Trim(NodeList(i).childNodes(j).text) & "<br/><br/>"
'            end if
'        next
    next

    if Len(outstr) = 0 then
        Response.write "<br/> Error: Unable to communicate with Fedex Server. Please check your Internet connection.<br/>"
    else
        Response.Write outstr
    end if
%>

Now run this page in Internet Explorer and you will see the response in XML.

ListView like Android Market Application with separator and ColdFusion as web server


Hi folks. This time I’m presenting a huge post.

This post will cover following things:

  • ListView with separator
  • Pagination  like Android Market application

I know that not all of you knows ColdFusion and its component (cfc), but it is just a server part like your web service code.

myWebservice.cfc

<cfcomponent displayname="myWebservice">
	<cffunction name="getJobs" access="remote" output="false" returntype="struct">
		<cfargument name="currentPage" required="true" type="numeric" default='1' />
		<cfargument name="totalRecord" required="true" type="numeric" default="10" />
		<cfargument name="searchString" required="false" type="string" default="" />
		<cfset var qResult = "">
		<cfset var condition = "" />
		<cfset var startRow = (arguments.CurrentPage-1) * arguments.TotalRecord +1 />
		<cfset var endRow = startRow + arguments.TotalRecord -1 />
		<cfset var qGetAllRecord = "" />
		<cfset var gridStruct = "" />
		<cfif len(arguments.searchString)>
			<cfset condition = condition & " -- your search conditions goes here" />
		</cfif>
		<cfstoredproc procedure="usp_Pagination" datasource="#application.DSN#" username="#application.DBUID#" password="#application.DBPWD#">
			<cfprocresult name="qGetAllRecord" resultset="1">
			<cfprocresult name="qtotalRecord" resultset="2">
			<cfprocparam dbvarname="@SqlColumns" cfsqltype="CF_SQL_VARCHAR" value="*">
			<cfprocparam dbvarname="@SqlFriendlyColumns" cfsqltype="CF_SQL_VARCHAR" value="*">
			<cfprocparam dbvarname="@SqlTableClause" cfsqltype="CF_SQL_VARCHAR" value="Jobs">
			<cfprocparam dbvarname="@StartRow" cfsqltype="CF_SQL_VARCHAR" value="#startRow#">
			<cfprocparam dbvarname="@EndRow" cfsqltype="CF_SQL_VARCHAR" value="#endRow#">
			<cfprocparam dbvarname="@SqlWhere" cfsqltype="CF_SQL_VARCHAR" value="#condition#">
			<cfprocparam dbvarname="@SqlRowNumOrderBy" cfsqltype="CF_SQL_VARCHAR" value="Jobs.createdDate desc">
			<cfprocparam dbvarname="@SqlOuterOrderBy" cfsqltype="CF_SQL_VARCHAR" value="createdDate desc">
		</cfstoredproc>
		<cfset gridStruct=StructNew() />
		<cfset gridStruct.query = qGetAllRecord />
		<cfset gridStruct.totalRowCount=qtotalRecord.countAll />
		<cfreturn qResult>
	</cffunction>
</cfcomponent>

The reason behind showing this code is to let you know the implementation of the server part.

In above function, I am returning fix number of records from my database. It is used to pull out ten ten records from a query that has thousands of records.

Now I’m calling this web service like:

http://localhost/cfc/mywebservice.cfc?returnformat=json&method=getJobs&currentPage=5&totalRecord=10

And it returns a data in JSON format like:

{“QUERY”:{“COLUMNS”:[“JOBID”,”JOBTITLE”,”CREATEDATE”,”JOBDETAIL”],”DATA”:[[“1″,”Title1″,”January, 25 2011 10:55:53″,”Detail is here”],[“2″,”Title2″,”January, 25 2011 10:55:53″,”Detail is here”],[“3″,”Title3″,”January, 20 2011 14:13:10″,”Detail is here”],[“4″,”Title4″,”January, 20 2011 14:13:10″,”Detail is here”],[“5″,”Title5″,”January, 20 2011 14:13:10″,”Detail is here”],[“6″,”Title6″,”January, 20 2011 14:13:10″,”Detail is here”],[“7″,”Title7″,”January, 18 2011 16:23:28″,”Detail is here”],[“8″,”Title8″,”January, 17 2011 11:22:02″,”Detail is here”],[“9″,”Title9″,”January, 11 2011 09:22:32″,”Detail is here”],[“10″,”Title10″,”January, 11 2011 09:22:32″,”Detail is here”]]},”TOTALROWCOUNT”:”120″}

Now we are ready to build Android app.

joblist.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 	android:layout_width="fill_parent"
 	android:layout_height="fill_parent"
	android:orientation="vertical">
 <EditText android:id="@+id/JobSearch"
 		android:layout_height="wrap_content"
		android:layout_width="fill_parent"
		android:singleLine="true"
 		android:hint="Search"/>
	<ListView android:id="@+id/JobList"
 		android:layout_width="fill_parent"
		android:layout_height="wrap_content" />
	<TextView android:id="@+id/EmptyJobList" android:layout_width="fill_parent"
		android:layout_height="fill_parent" android:text="No Results" android:visibility="invisible" />
</LinearLayout>

joblistheader.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="wrap_content">
	<TextView android:id="@+id/JobDate" android:layout_width="fill_parent"
		android:layout_height="wrap_content" android:gravity="center"
		style="?android:attr/listSeparatorTextViewStyle" />
</LinearLayout>

joblistitem.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	android:orientation="vertical" android:layout_width="fill_parent"
	android:layout_height="wrap_content" android:paddingRight="5px">
	<TextView android:id="@+id/JobTitle" android:layout_width="wrap_content"
		android:layout_height="wrap_content" android:layout_alignParentLeft="true"
		android:text="jobTitle" style="?android:attr/textAppearanceLarge" />
	<TextView android:id="@+id/JobDetail"
		android:layout_width="fill_parent" android:layout_height="wrap_content" />
</LinearLayout>

And MyJobListView.java

package com.isummation.listview;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.TreeSet;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MyListView extends Activity {
	private static boolean isInitialized;
	private static int JOBID_IDX;
	private static int JOBTITLE_IDX;
	private static int CREATEDDATE_IDX;
	private static int JOBDETAIL_IDX;
	private JobListAdapter jobListAdapter;
	private long TotalRowCount;
	private int totalRecordPerCall = 20;
	private Date lastDate;
	private EditText JobSearch;
	private ListView list;

	class JobListRowData {
		boolean isHeader;
		Date jobCreationDate;
		int jobId;
		String jobTitle;
		String jobDetail;
	}

	class JobListAdapter extends BaseAdapter {
		private static final int TYPE_ITEM = 0;
		private static final int TYPE_SEPARATOR = 1;
		private static final int TYPE_MAX_COUNT = TYPE_SEPARATOR + 1;
		private LayoutInflater mInflater;
		private ArrayList mData = new ArrayList();
		private TreeSet mSeparatorsSet = new TreeSet();
		private int count = 0;
		private boolean isCleared = true;

		public JobListAdapter() {
			mInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			initialize();
		}

		public void ParseJSONArray(JSONArray JQueryData) {
			int len = JQueryData.length();

			final TextView EmptyListView = (TextView) findViewById(R.id.EmptyJobList);

			if (TotalRowCount == 0) {
				EmptyListView.setVisibility(View.VISIBLE);
			} else {
				EmptyListView.setVisibility(View.INVISIBLE);
			}
			try {
				for (int i = 0; i &lt; len; i++) {

					Date tempDate = new Date(JQueryData.getJSONArray(i)
					.getString(CREATEDDATE_IDX));

					if (lastDate == null) {
						JobListRowData jobListRowData = new JobListRowData();
						jobListRowData.isHeader = true;
						jobListRowData.jobCreationDate = new Date(JQueryData.getJSONArray(i)
								.getString(CREATEDDATE_IDX));
						addSeparatorItem(jobListRowData);

						jobListRowData = new JobListRowData();
						jobListRowData.jobId = JQueryData.getJSONArray(i)
								.getInt(JOBID_IDX);
						jobListRowData.jobTitle = JQueryData.getJSONArray(i)
								.getString(JOBTITLE_IDX);
						jobListRowData.jobDetail = JQueryData.getJSONArray(i)
								.getString(JOBDETAIL_IDX);
						addItem(jobListRowData);

						lastDate = new Date(JQueryData.getJSONArray(i)
								.getString(CREATEDDATE_IDX));
					} else if (lastDate.getDate() == tempDate.getDate()
							&amp;&amp; lastDate.getMonth() == tempDate.getMonth()
							&amp;&amp; lastDate.getYear() == tempDate.getYear()) {
						JobListRowData jobListRowData = new JobListRowData();
						jobListRowData.jobId = JQueryData.getJSONArray(i)
								.getInt(JOBID_IDX);
						jobListRowData.jobTitle = JQueryData.getJSONArray(i)
								.getString(JOBTITLE_IDX);
						jobListRowData.jobDetail = JQueryData.getJSONArray(i)
								.getString(JOBDETAIL_IDX);
						addItem(jobListRowData);
					} else {
						JobListRowData jobListRowData = new JobListRowData();
						jobListRowData.isHeader = true;
						jobListRowData.jobCreationDate = new Date(JQueryData.getJSONArray(i)
								.getString(CREATEDDATE_IDX));
						addSeparatorItem(jobListRowData);
						lastDate = new Date(JQueryData.getJSONArray(i)
								.getString(CREATEDDATE_IDX));

						jobListRowData = new JobListRowData();
						jobListRowData.jobId = JQueryData.getJSONArray(i)
								.getInt(JOBID_IDX);
						jobListRowData.jobTitle = JQueryData.getJSONArray(i)
								.getString(JOBTITLE_IDX);
						jobListRowData.jobDetail = JQueryData.getJSONArray(i)
								.getString(JOBDETAIL_IDX);
						addItem(jobListRowData);
					}

				}
			} catch (Exception e) {
				Toast.makeText(getApplicationContext(), e.getMessage(),
						Toast.LENGTH_LONG).show();
				Log.e(e.getClass().getName(), e.getMessage(), e);
				TotalRowCount = 0;
			}
		}

		public void initialize() {
			isCleared = false;
			count = 0;
			lastDate = null;
			mSeparatorsSet.clear();
			mData.clear();
			JSONArray JQueryData = getJobs(1);
			ParseJSONArray(JQueryData);
			isCleared = true;
		}

		public void addMoreData() {
			if (jobListAdapter.count &lt; TotalRowCount &amp;&amp; isCleared) { 
				JSONArray JQueryData = getJobs((jobListAdapter.count + totalRecordPerCall)
						/ totalRecordPerCall + 1);
				ParseJSONArray(JQueryData);
			}
		}

		public void addItem(final JobListRowData item) {
			mData.add(item);
			count += 1;
			notifyDataSetChanged();
		}

		public void addSeparatorItem(final JobListRowData item) {
			mData.add(item);
			mSeparatorsSet.add(mData.size() - 1);
			notifyDataSetChanged();
		}

		public int getItemViewType(int position) {
			return mSeparatorsSet.contains(position) ? TYPE_SEPARATOR
					: TYPE_ITEM;
		}

		public int getViewTypeCount() {
			return TYPE_MAX_COUNT;
		}

		public int getCount() {
			return mData.size();
		}

		public JobListRowData getItem(int pos) {
			return mData.get(pos);
		}

		public long getItemId(int pos) {
			return pos;
		}

		@Override
		public boolean isEnabled(int position) {
			return mSeparatorsSet.contains(position) ? false : true;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder holder;
			int type = getItemViewType(position);
			if (convertView == null) {
				holder = new ViewHolder();
				switch (type) {
				case TYPE_ITEM:
					convertView = mInflater.inflate(R.layout.joblistitem, null);
					holder.text = (TextView) convertView
							.findViewById(R.id.JobTitle);
					holder.text2 = (TextView) convertView
							.findViewById(R.id.JobDetail);
					break;
				case TYPE_SEPARATOR:
					convertView = mInflater.inflate(R.layout.joblistheader,
							null);
					holder.text = (TextView) convertView
							.findViewById(R.id.JobDate);
					break;
				}
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			switch (type) {
			case TYPE_ITEM:
				holder.text.setText(mData.get(position).jobTitle);
				holder.text2.setText(mData.get(position).jobDetail);
				break;
			case TYPE_SEPARATOR:
				try {
					holder.text
							.setText(android.text.format.DateFormat.format(
									"MMM dd, yyyy",
									mData.get(position).jobCreationDate));
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(), e.getMessage(),
							Toast.LENGTH_LONG).show();
					Log.e(e.getClass().getName(), e.getMessage(), e);
				}
				break;
			}
			return convertView;
		}

		class ViewHolder {
			TextView text;
			TextView text2;
		}
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.joblist);

		JobSearch = (EditText) findViewById(R.id.JobSearch);
		JobSearch.setImeOptions(EditorInfo.IME_ACTION_SEARCH);
		JobSearch.setOnKeyListener(new View.OnKeyListener() {

			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (keyCode == KeyEvent.KEYCODE_ENTER
						&amp;&amp; event.getAction() == KeyEvent.ACTION_DOWN) {
					jobListAdapter.initialize();
				}
				return false;
			}
		});

		jobListAdapter = new JobListAdapter();

		list = (ListView) findViewById(R.id.JobList);
		list.setAdapter(jobListAdapter);
		list.setOnScrollListener(new AbsListView.OnScrollListener() {

			public void onScrollStateChanged(AbsListView view, int scrollState) {

			}

			public void onScroll(AbsListView view, int firstVisibleItem,
					int visibleItemCount, int totalItemCount) {
				boolean loadMore = firstVisibleItem + visibleItemCount &gt;= totalItemCount;
				if (loadMore) {
					jobListAdapter.addMoreData();
				}
			}
		});

		list.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<!--?--> parent, View view,
					int position, long id) {
				JobListRowData item = jobListAdapter.getItem(position);
				if (!item.isHeader) {
					// start another activity
				}
			}
		});
	}

	public JSONArray getJobs(int currentPage) {
		try {
			String searchString = JobSearch.getText().toString();
			HttpClient httpClient = new DefaultHttpClient();
			HttpContext localContext = new BasicHttpContext();
			HttpGet httpGet = new HttpGet(
					"http://10.0.2.2/cfc/iphonewebservice.cfc?returnformat=json&amp;method=getJobs¤tPage="
							+ URLEncoder.encode("" + currentPage, "UTF-8")
							+ "&amp;totalRecord="
							+ totalRecordPerCall
							+ "&amp;searchString="
							+ URLEncoder.encode(searchString, "UTF-8"));
			HttpResponse response = httpClient.execute(httpGet, localContext);

			BufferedReader reader = new BufferedReader(new InputStreamReader(
					response.getEntity().getContent(), "UTF-8"));
			String sResponse = reader.readLine();
			JSONObject JResponse = new JSONObject(sResponse);
			JSONObject JQuery = JResponse.getJSONObject("QUERY");
			TotalRowCount = JResponse.getLong("TOTALROWCOUNT");
			JSONArray JQueryColumns = JQuery.getJSONArray("COLUMNS");

			if (!isInitialized) {
				int len = JQueryColumns.length();
				for (int i = 0; i &lt; len; i++) {
					if (JQueryColumns.getString(i).equals("JOBID")) {
						JOBID_IDX = i;
					} else if (JQueryColumns.getString(i).equals("JOBTITLE")) {
						JOBTITLE_IDX = i;
					} else if (JQueryColumns.getString(i).equals("CREATEDATE")) {
						CREATEDDATE_IDX = i;
					} else if (JQueryColumns.getString(i).equals(
							"JOBDETAIL")) {
						JOBDETAIL_IDX = i;
					}
				}
				isInitialized = true;
			}

			return JQuery.getJSONArray("DATA");
		} catch (Exception e) {
			Toast.makeText(getApplicationContext(), e.getMessage(),
					Toast.LENGTH_LONG).show();
			Log.e(e.getClass().getName(), e.getMessage(), e);
			finish();
			return new JSONArray();
		}
	}
}

Update:

I’ve updated above code, for “Loading…” effect while getting next 20 records.
You can now download the source code.
Download source code

SplendidCRM is copy of SugarCRM?


Hi,

Now a days I’m reviewing all open source CRM. Till now I have seen SugarCRM, vTiger, SplendidCRM etc.

They are also providing web services to integrate our application to CRM.

SpledidCRM is built over Asp.net, so it is but obvious that it’s web service will be in .net.

When I browse it to include it in my sample web site, I surprised!

So Splendid programmer forget to change the name of web service? lol!