This post, as promised, is a continuation of the prior post. If you recall, last week I discussed how to get the location information from your user’s device. Today, I will show how we can use that data to send and parse a request to a RESTful web application. In the examples I have provided, I am simply using the location information to get weather data sent back to the application. However, the techniques I use to parse the XML can be used with any RESTful web application that supports XML.
- The first thing that we need to do is create a method that accepts one argument. The argument is a string that will be the URL that we will be using to access the XML document. Refer to last weeks post where I showed how we implemented the variable named currentURL, and how we used the current location to customize the URL. If you look at the example below you will notice that we are creating this method to read the XML document. In the next step, you will see how we call this method and this parse the XML.
If you look at the XML document below you can see exactly how we are parsing it from the above code. Notice how in the code above we are getting elements with the tag name “data”. And then we are getting the element data that has the attribute “forecast”. Now look at the XML document and you can see a tag named “data” who has an attribute named “forecast”. Then, within that element, we get the tag that is named “time-layout”. From this point, we use the ChildNodes designation to get information from the children of the “time-layout” element. Remember that we start counting from 0. Thus, the second child node will have the subscript 1. In this example, we are just getting the forecast information for certain time periods. However, using similar methods we could get all sorts of information from other RESTful web apps.
- From this point, it is up to you to do with the information from the XML what you will. You could display the information to the user in a List or even just a TextView widget. This step will be the focus of next weeks post where I will show how we can bind the data that we get from an XML to a List and then render that List to the user.
Now, this has been a rather quick tutorial as I am running short on time. Please, if you have any questions on the material, feel free to add them to the comments section below. Remember to share this post by clicking the buttons below.