Quantcast
Viewing latest article 2
Browse Latest Browse All 7

Creating an Android App with PHP JSON Backend – Part II

The next part of our project is where things move over into Android land. We’ve created a pretty simple API to utilize, now lets put together the Java code required to pull data from this thing and test on our device. To start I’ve created a new project in Eclipse:

Image may be NSFW.
Clik here to view.

We’ll let Eclipse create the default activity and work within it to get things up and running. Next we’ll go ahead and modify the default view that was created to give the TextView an ID, so it is easy to retrieve a reference to it from our Activity. We’ll use this TextView to print debug information and output until we design a proper interface. Open up res/layout/main.xml and edit the TextView as follows:

<?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="fill_parent"
    >
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    android:id="TextView1"/>
</LinearLayout>

Next we'll need to add permissions to our app to access the network at large. Open the AndroidManifest.xml file and add the following line after the application tag:

<uses-permission android:name="android.permission.INTERNET" />

This tag will allow for the application to have full access to the network.

Finally lets write some code! We'll be using the org.json and org.apache.http packages in this project, to provide JSON encoding/decoding and HTTP services respectively. The first piece of code will be to construct our request packet. It turns out that in practice this is pretty simple. We just create an empty JSONObject instance, and call the put method:

    	JSONObject j = new JSONObject();
    	try {
    		j.put("action", "getQuote");
		} catch (JSONException e1) {
			e1.printStackTrace();
		}

So far so good, next lets take this JSON request and push it through the pipes at our quote request server. To do this we'll create a new HttpClient, and run a HttpPost constructed with the toString output of our JSON object. For now we'll simply take the output and push it to the TextView we IDed in the first step.

        // Create a new HttpClient and Post Header
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost("http://url/to/your/file/mobileServ.php");
        TextView tv1 = (TextView) findViewById(R.id.TextView1);

        try {
            // Add your data
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);

            // Add two POST request variables
            nameValuePairs.add(new BasicNameValuePair("APIKey", "ultraQuote"));
            nameValuePairs.add(new BasicNameValuePair("payload", j.toString()));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

            // Execute HTTP Post Request
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();

            // Get the return string (JSON data)
            String temp = EntityUtils.toString(entity);

            tv1.setText(temp);

        } catch (ClientProtocolException e) {

        } catch (IOException e) {

        }

Running this on your device should yield an app with text very similar to the example JSON responses we looked at in part one. Let's parse this response and extract the data finally, replacing the tv1.setText(temp) with the following code.

            try {
            	// create an object holding the JSON data
            	JSONObject j1 = new JSONObject(temp);

            	// quotes are stored in an array, provisioned for sending more than one.
            	// we get this array next, called quote.
				JSONArray quotes = j1.getJSONArray("quote");

				// select the first item in the array.
				JSONObject q1 = quotes.getJSONObject(0);

				// build output string.
				String quoteText = q1.getString("quote");
				String quoteAuthor = q1.getString("author");

				tv1.setText(quoteText + "\n -" + quoteAuthor);

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

Running code now should result in a quote appearing on your device, and that's all there is to it! In the final part of this tutorial I'll cover some basic error handling and UI development to round off this application.


Viewing latest article 2
Browse Latest Browse All 7

Trending Articles