Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

Mobile Application Integrations: XML on the client

In this article we will discuss about mobile application integration using xml on client side. We will also implement a simple Android client for this API.

Introduction

I have chosen to target low-end current generation (as of 2013) smartphones . These devices are typically fairly resource-constrained (free storage space on the phone’s integrated flash is typically counted in the low tens of megabytes, and application run time heaps are generally limited to 32MB) and often run older versions of Android (typically version 2.2 or 2.3) with low resolution displays (320x240 is common). It is important to bear in mind these restrictions while developing applications for this kind of device. It goes without saying that a developer should have a device of the lowest specification targeted for testing purposes; it is also important, however, to use the device along with the application being developed on a day to day basis, as this is the only way to get a true feel for how the other applications on the phone will affect its performance.

In this article, I will implement a simple Android client for this API. I assume that the client will have an always-available connection to the server, so I do not need to worry about offline storage of data. Data is downloaded on-demand immediately prior to display, and requests are sent back to the server immediately in response to user commands.

XML File

Figure 1: XML File

Developing the app

To develop the application, I am using Eclipse with the Android Developer Tools plugin. I highly recommend this combination as it is Google’s only officially-supported integrated environment, so most of the Android documentation and samples as well as many third-party books and articles will assume that this is the environment you are using.

To begin, allow Eclipse to set up an Android Application project; it will ask for a variety of information. As well as naming the project, you need to specify a package name (I used com.example.simplespringclient, as I had called the web application’s project simplespring), and choose the versions of Android you want to target. You can choose to use a higher SDK version than your minimum targeted version; doing so allows you to use more modern features of Android when they are available.

Create an initial Activity object using Eclipse’s wizard, selecting a “blank” activity from the list of options. Blank is the simplest and most portable option, as it does not require any advanced features. Of the other types, only the “master and details” activity is really suitable for this kind of application, but as it requires a higher minimum version of Android than I have chosen I cannot use it. I called my first activity CustomerListActivity. Once it has finished creating the Activity, Eclipse automatically opens the layout it has created for it, which you will need to edit. My plan for this activity is to just present a list of customers as the main interface; extra commands will be added to the activity’s options menu. Delete the text view control Eclipse places on the layout by default, and replace it with a ListView object, and give it a useful id.

Now we have a suitable layout, we need to look at some code. The first place to start with an Android activity is usually its onCreate method. Eclipse has generated a stub for us that fulfils the basic requirements: it calls super.onCreate - Android will throw an exception if we fail to do this - and loads the layout it created for us. We’ll also need to set up any event handlers we want on the controls, create extra objects we need, and initiate a data download.

Listing 1: The finished onCreate method

 
    private ListView customerList;
    private Serializer xml;

    protected void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_customer_list);
        customerList = (ListView) findViewById (R.id.customerList);
        customerList.setOnItemClickListener(viewAccounts);
        xml = new Persister ();
        download();
    }

We find the customer list and set a handler for what to do when an item is clicked (We’ll actually define viewAccounts later; for now you can just let Eclipse create the field for you if you want). We need a Persister from SimpleXML in order to translate XML documents into Java objects (you’ll need to add the SimpleXML jar file to your project, which can most easily be achieved by dropping a copy of it in the ‘libs’ folder; Eclipse will automatically add the dependency to your project). Then we call a function (which we still need to create) that will download the data. I’ve put it in a separate function because we’ll add a menu item to refresh the list later, and we can then call the same function there.

Listing 2: The download function

 
	private ProgressDialog progressDialog;
	private AsyncTask<Void, Void, Result> downloadInProgress;
	private DialogInterface.OnCancelListener onCancelListener = new DialogInterface.OnCancelListener() 
	{
		@Override
		public void onCancel(DialogInterface dialog)
		{
			if (downloadInProgress != null)
				downloadInProgress.cancel(true);
			progressDialog.dismiss();
		}
	};

	private void download()
	{
		if (downloadInProgress != null)
			downloadInProgress.cancel(true);
		downloadInProgress = new DownloadTask().execute();
		progressDialog = new ProgressDialog(this);
		progressDialog.setCancelable(true);
		progressDialog.setOnCancelListener(onCancelListener);
		progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
		progressDialog.setMessage("Downloading customer list");
		progressDialog.show();
	}

The download function is quite simple, as it defers most of the work to an object of a class we’ll create next, DownloadTask. It first checks for an existing DownloadTask and cancels it if it finds one. Then it starts a new DownloadTask, and while that’s working on the download sets up and displays a progress dialog. The progress dialog has a cancel button; if it’s pressed, we cancel the DownloadTask.

Listing 3: The DownloadTask

 
	class DownloadTask extends AsyncTask<Void, Void, Result>
	{
		@Override
		protected Result doInBackground (Void... params)
		{
			HttpClient client = new DefaultHttpClient ();
			try
			{
				HttpResponse response = client.execute (new HttpGet (
					"http://192.168.1.101:8080/simplespring/xml/customers"));
				if (response.getStatusLine ().getStatusCode () != 200)
					return Result.error (
						response.getStatusLine ().getReasonPhrase ());
				
				HttpEntity entity = response.getEntity();
				String contentType = entity.getContentType().getValue();
				if (!contentType.startsWith("text/xml"))
					return Result.error (
						"Did not receive XML response (content type was: " + 
						contentType + ")");
				
				return xml.read(Result.class, entity.getContent());
			}
			catch (Exception e)
			{
				return Result.error (e.toString());
			}
		}

		@Override
		protected void onPostExecute(Result result)
		{
			super.onPostExecute(result);
			progressDialog.dismiss();
			downloadInProgress = null;
			if (result.isError())
			{
				Toast.makeText(CustomerListActivity.this, 
						result.getError(), 
						Toast.LENGTH_LONG).show ();
			}
			else
			{
				customerAdapter = new ArrayAdapter<Customer>(
						CustomerListActivity.this,
						android.R.layout.simple_list_item_1,
						result.getCustomers());
				customerList.setAdapter(customerAdapter);
			}
		}
	};

DownloadTask is implemented using the Android utility class AsyncTask. AsyncTask splits a task into two portions, one of which is performed in a background thread (the doInBackground method), the other is performed in the main application thread after the background thread is completed (onPostExecute). It also provides a facility for handling progress updates in the main application thread during execution, but we are not using that here. We are using two additional application-supplied classes here, Result and Customer. These are classes copied directly from the server application, albeit with any data access related code stripped out (i.e., in Customer, the method getAccounts(AccountDAO) has been removed). I have also added accessor methods to Result that were not needed in the server (including isError(), returning true if ‘success’ is false and vice versa, which I find helps with the readability of the code), and a toString() method in Customer that returns the customer’s name (which makes placing the customers in a list somewhat easier).

In the background thread, we use the DefaultHttpClient class (part of a cut-down version of the Apache HttpClient library that is included in the Android standard libraries) to initiate the request. We check for a couple of error conditions (server returned error, or the result was not XML), and assuming neither were detected we use the persister object we created earlier to convert the XML to a Java Result object.

Back in the main application thread, we dismiss the progress dialog, note that no download task is in progress any more, and check whether the result indicates an error occurred. If an error occurred we display it using Android’s “toast” facility. Otherwise, we pass the results to the list view for display.

Adding a refresh menu item is now simple. Eclipse has already created and initialised an options menu for the activity; simply find it in res/menus/customer_list.xml and replace the default ‘preferences’ item with one to refresh the list. Then we just need to call the download method when it’s selected:

Listing 4: Responding to a refresh command

 
	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item)
	{
		switch (item.getItemId())
		{
		case R.id.refresh:
			download ();
			return true;
		}
		return false;
	}

It would also be useful to automatically refresh the list when we return to it from other activities:

Listing 5: Responding Refreshing on resume

 
	@Override
	protected void onResume()
	{
		super.onResume();
		if (downloadInProgress == null)
			download();
	}

Using this simple approach we can display any simple list of data items. Adding more functions such as forms for sending data back to the server or activities to show structured data is not difficult, and I will tackle both of these tasks in my next article.

This is all for this article. See you next time.



My main area of specialization is Java and J2EE. I have worked on many international projects like Recorders,Websites,Crawlers etc.Also i am an Oracle Certified java professional as well as DB2 certified

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login