Accessing RESTful APIs From An Android Application
I'm currently in the midst of writing my first Android application. Android is Google's new open source OS for mobile devices.
Just for fun, I'm writing an application called Complainatron. Complainatron is an application that allows mobile users to bitch randomly about the things that bother them. Users are able to view and vote on other peoples' complaints. Additionally, within the mobile application, users can see where various complaints originated via Google maps.
The application consists of 2 components. Firstly there is the Android application that runs on a user's mobile device. Second, there is the Complainatron API, a RESTful API build using Sinatra, a lightweight Ruby web framework. The web API returns all responses as JSON. This keeps the payload reasonably small.
The Complainatron client interacts with the web API to get lists of complaints and to submit new complaints.
How does the mobile client do this? Android is based on Java, so for the most part is should be a fairly famililar process: make a web request to the API and parse the results. Here's an example of a GET request:
Fairly straightforward, right?
Converting the response to a string for processing is nothing complicated. Just loop over the stream, reading line by line and build up a string.
The next step is to create objects from the response. I achieve this using the classes from the org.json package. These classes include JSONArray, JSONObject and others. Essentially you just need to create a new JSONArray with the response from the web API.
From there, it's simply a matter of looping over the JSONObjects within the JSONArray and creating your domain specific objects from each.
Ultimately, what I end up with is a collection of domain specific objects. In this case, Complaints. These can then be used within the Android Actions to display data to the user, be it in a list, table or map.
I'll write more on this as I go.


No comments have been posted.