Skip to content

X.commerce Android Apps the Easy Way, Part 2: Accessing Web APIs

August 10, 2011

This is the second installment in my series showing you how to use Google’s App Inventor for Android tool and eBay web APIs to build mobile commerce applications for Android-based devices.

The previous article introduced App Inventor, how to setup the software and start using it, how to share App Inventor projects and apps, and some of App Inventor’s limitations. If you don’t already have App Inventor installed, please revisit the previous article and work through the setup and testing steps so you are ready to follow along below.

This time, I will focus on the available App Inventor components and especially on how to access RESTful web APIs using the “Web” component. This will set you up to succeed with building an Android eBay commerce app in the final two articles of the series.

App Inventor components

Click here to access the full App Inventor reference documentation. This contains information on the various components you can select from in the App Inventor Designer as well as docs for the blocks available in the App Inventor Blocks Editor. (If you need a refresher on the Designer or the Editor, please refer to part 1 of this series.) The reference pages also discuss some of the key concepts to wrap your head around if you want to have smooth sailing in building Android apps with App Inventor.

For now, let’s focus on the available components. The reference pages break the components out into groups just as they are arranged in the Designer interface. The groups are:

It’s worth your time to at least skim through the various components so you can get a feel for what operations are possible and which components you would use to carry them out. For more information, you can refer to community submitted App Inventor tutorials on a variety of topics and sticking points by clicking here.

Now that you have a high level understanding of the various components available to you, let’s get started creating an app to interact with an example arbitrary web API using the “Web” component.

Creating app components

To start, launch App Inventor (click here or navigate to http://appinventor.googlelabs.com). Create a new project. I’ve called mine “Web_API_Example”.

Suppose that we want to build an Android application that asks its user to enter some location of interest. This may be a street address, a ZIP code, or something even more vague such as a landmark name. We’d like to enable the user to enter whatever location they like, then have our app query the freely available Yahoo PlaceFinder to attempt to geocode the given location and return useful location information about it. We can then display whatever information we want from the response, for instance the latitude and longitude coordinates. How would we build an app like that?

First note that in order to use PlaceFinder, you need to have a Yahoo Application ID. This is used to identify your application in caes of policy abuse or over usage and is a typical requirement of many web APIs these days. No problem, click here to create one.

Once you have your ID, you are ready to create your app. Drag a TextBox1 component into the Designer app screen for the location field, a Button1 to submit that location to PlaceFinder, a TableArrangement1 to contain the resulting latitude and longitude value and label components, and a Web component to submit the entered location to the PlaceFinder via HTTP GET. After renaming and changing some of the default values for the various components, our design might look something like this:

Web API calls

The PlaceFinder Guide details how to format your web API call. Be sure to read through the Requests page as well as the provided Examples. For our purposes, let’s specify a query with a JSON response (flags=J parameter) with a free form single line address. Note that we encode spaces in an address with the + (plus character). The format therefore would be:

http://where.yahooapis.com/geocode?flags=J&appid=yourappid&location=yourstreet,+yourcity,+otherlocationinfo

For instance, querying for PayPal’s San Jose offices at 2211 North 1st Street, San Jose, CA 95131 would be done with a query such as:

http://where.yahooapis.com/geocode?flags=J&appid=yourappid&location=2211+North+1st+Street,+San+Jose,+CA+95131

Submitting the above query with your valid Application ID in place of yourappid should result in the following JSON response from PlaceFinder:


{ "ResultSet" : { "Error" : 0,
      "ErrorMessage" : "No error",
      "Found" : 1,
      "Locale" : "us_US",
      "Quality" : 87,
      "Results" : [ { "city" : "San Jose",
            "country" : "United States",
            "countrycode" : "US",
            "county" : "Santa Clara County",
            "countycode" : "",
            "hash" : "92F01C6AC1A15F33",
            "house" : "2211",
            "latitude" : "37.377919",
            "line1" : "2211 N 1st St",
            "line2" : "San Jose, CA  95131-2021",
            "line3" : "",
            "line4" : "United States",
            "longitude" : "-121.921842",
            "name" : "",
            "neighborhood" : "",
            "offsetlat" : "37.377858",
            "offsetlon" : "-121.921980",
            "postal" : "95131-2021",
            "quality" : 87,
            "radius" : 500,
            "state" : "California",
            "statecode" : "CA",
            "street" : "N 1st St",
            "unit" : "",
            "unittype" : "",
            "uzip" : "95131",
            "woeid" : 12797582,
            "woetype" : 11,
            "xstreet" : ""
          } ],
      "version" : "1.0"
    } }

Likewise, you might submit a landmark name and country based query such as the following for the Eiffel Tower:

http://where.yahooapis.com/geocode?flags=J&appid=yourappid&location=eiffel+tower,+france

which would return a similarly structured JSON response as follows:


{ "ResultSet" : { "Error" : 0,
      "ErrorMessage" : "No error",
      "Found" : 1,
      "Locale" : "us_US",
      "Quality" : 90,
      "Results" : [ { "city" : "Paris",
            "country" : "France",
            "countrycode" : "FR",
            "county" : "Paris",
            "countycode" : "75",
            "hash" : "",
            "house" : "",
            "latitude" : "48.858189",
            "line1" : "Eiffel Tower",
            "line2" : "75007 Paris",
            "line3" : "",
            "line4" : "France",
            "longitude" : "2.294490",
            "name" : "Eiffel Tower",
            "neighborhood" : "",
            "offsetlat" : "48.858189",
            "offsetlon" : "2.294490",
            "postal" : "75007",
            "quality" : 90,
            "radius" : 100,
            "state" : "Ile-de-France",
            "statecode" : "",
            "street" : "",
            "unit" : "",
            "unittype" : "",
            "uzip" : "75007",
            "woeid" : 22907017,
            "woetype" : 20,
            "xstreet" : ""
          } ],
      "version" : "1.0"
    } }

You can do all sorts of things with the responses you get back from PlaceFinder. For our purposes, we merely want to display the location coordinates.

Wiring up blocks

It’s time to open the App Inventor Blocks Editor and hook up our app components. Launch the Editor from the upper right of the Designer interface. Once it loads you can begin hooking together your components’ methods and properties to be executed and set when certain events are generated during app execution.

First, we need to setup the chain that processes input. Select your button, then its Button.Click method. You can then drag in the Web.Url property and supporting components including Web.Get to generate and issue the web API call. Note that you need to use the Web.UriEncode method to encode the location input from the user so that it can be correctly appended to the web API call’s URL. When everything is wired up, the input portion of your app should look something like this (with yourappid replaced by your own ID, of course):

Now that we have our input wired together, we need to drag and wire up the logic to process and display the coordinates returned by the PlaceFinder web API.

For each of the latitude and longitude values, we use the JSON response content, along with a start and end tag from that content, to parse out the pertinent coordinate value. The values are then set via the lat and lon Label.Text properties.

Note how I define a new ParseJSONResponse component to handle the actual parsing. I also use a temporary text variable, tmpData, during parsing.

That’s it! We now have a complete, deployable Android application which queries a the Yahoo PlaceFinder web API and provides information back to the user based upon the user’s requested location. Not too bad, right?

Getting coordinates with our Android app

Now that the app is complete, let’s run it.

You can access and manipulate all of the source blocks from my project pictured above by downloading the project ZIP archive from GitHub (click here to download) and then selecting “More Actions” -> “Upload Source” in the main App Inventor window (see previous article for more on this process). The GitHub project is available from the “Downloads” button here: https://github.com/billday/App-Inventor-Web-Apps

Note: In order to execute the example, you will need to change the yourappid text in the input portion of the program logic in the Blocks Editor to be your own Yahoo Application ID as mentioned above.

You should spend some time working through the Designer and Editor until you thoroughly understand how and why the web API parsing and Android interface components used in this example work. You may also wish two review one of these two examples provided by other developers (I took inspiration from both as I prepared this article): Using the Web component to access Yahoo Finance stock information and the Google Books API.

If you fire up and connect to the emulator as discussed in the first installment in this series, you should now see:

Entering in a location and clicking the “Click to get coordinates” button should execute the call to the PlaceFinder web API and return lat/lon coordinates for the best match to the location you specify.

For instance, if you enter a location of “Eiffel Tower”, you should get back the following:

You can also download the example packaged as an Android application from GitHub: Click here to download the APK. You can run this directly on your own Android device so long as you have it configured to allow non-market apps.

Click here to read the complete article on the PayPal X Developer Network including some conclusions and information on what’s coming in the next part in the series.

Advertisement

From → Uncategorized

Comments are closed.

%d bloggers like this: