官术网_书友最值得收藏!

Reading data from remote XML via HTTPClient

The ability to consume and display feed data from the Internet, via RSS feeds or alternate APIs, is the cornerstone of many mobile applications. More importantly, many services that you may wish to integrate into your app will probably require you to do this at some point, so it is vital to understand and be able to implement remote data feeds and XML. Our first recipe in this chapter introduces some new functionality within Titanium to help facilitate this need.

If you are intending to follow the entire chapter and build the MyRecipes app, then pay careful attention to the Getting Ready section for this recipe, as it'll guide you through setting up the project.

Getting ready

To prepare for this recipe, open Appcelerator Studio, log in and create a new mobile project, just as you did in Chapter 1: Building Apps Using Native UI Components. Select Classic and Default Project, then enter MyRecipes as the name of the app, and fill in the rest of the details with your own information, as you've done previously.

The complete source code for this chapter can be found in the /Chapter 2/RecipeFinder folder.

How to do it...

Now that our project is set up, let's get down to business! First, open your app.js file and replace its contents with the following:

// this sets the background color of the master View (when there are no windows/tab groups on it)
Ti.UI.setBackgroundColor('#000');

// create tab group
var tabGroup = Ti.UI.createTabGroup();

var tab1 = Ti.UI.createTab({
    icon:'cake.png',
    title:'Recipes',
    window:win1
});


var tab2 = Ti.UI.createTab({  
    icon:'heart.png',
    title:'Favorites',
    window:win2
});

//
//  add tabs
//
tabGroup.addTab(tab1);
tabGroup.addTab(tab2);


// open tab group
tabGroup.open();

This will get a basic TabGroup in place, but we need two windows, so we create two more JavaScript files called recipes.js and favorites.js. We'll be creating a Window instance in each file in the same way that we created the window2.js and chartwin.js files in Chapter 1: Building Apps Using Native UI Components.

In recipes.js, insert the following code. Do the same with favorites.js, ensuring that you change the title of the Window to Favorites:

//create an instance of a window
module.exports = (function() {

  var win = Ti.UI.createWindow({
    title : 'Recipes',
backgroundColor : '#fff'
  });

  return win;

})();

Next, go back to app.js, and just after the place where the TabGroup is defined, add this code:

var win1 = require("recipes");
var win2 = require("favorites");

Open the recipes.js file. This is the file that'll hold our code for retrieving and displaying recipes from an RSS feed. Type in the following code at the top of your recipes.js file; this code will create an HTTPClient and read in the feed XML from the recipe's website:

  //declare the http client object
var xhr = Ti.Network.createHTTPClient();

function refresh() {
    //this method will process the remote data
    xhr.onload = function() {
        console.log(this.responseText);
    };

    //this method will fire if there's an error in accessing the //remote data
    xhr.onerror = function() {
        //log the error to our Appcelerator Studio console
        console.log(this.status + ' - ' + this.statusText);
    };

    //open up the recipes xml feed
    xhr.open('GET', 'http://rss.allrecipes.com/daily.aspx?hubID=79');

    //finally, execute the call to the remote feed
    xhr.send();
}

refresh();

Try running the emulator now for either Android or iPhone. You should see two tabs appear on the screen, as shown in the following screenshot. After a few seconds, there should be a stack of XML data printed to your Appcelerator Studio console log:

How it works…

If you are already familiar with JavaScript for the Web, this should make a lot of sense to you. Here, we created an HTTPClient using the Ti.Network namespace, and opened a GET connection to the URL of the feed from the recipe's website using an object called xhr.

By implementing the onload event listener, we can capture the XML data that has been retrieved by the xhr object. In the source code, you'll notice that we have used console.log() to output information to the Appcelerator Studio screen, which is a great way of debugging and following events in our app. If your connection and GET request were successful, you should see a large XML string output in the Appcelerator Studio console log. The final part of the recipe is small but very important: calling the xhr object's send() method. This kicks off the GET request, without which your app would never load any data. It is important to note that you'll not receive any errors or warnings if you forget to implement xhr.send(), so if your app is not receiving any data, this is the first place to check.

Note

If you are having trouble parsing your XML, always check whether it is valid first! Opening the XML feed in your browser will normally provide you with enough information to determine whether your feed is valid or has broken elements.

主站蜘蛛池模板: 镇坪县| 雅江县| 公安县| 陈巴尔虎旗| 宁海县| 定兴县| 钟山县| 三穗县| 嘉义县| 浠水县| 乐至县| 平谷区| 嫩江县| 英山县| 南陵县| 新余市| 博爱县| 会同县| 年辖:市辖区| 凌源市| 通河县| 敦化市| 喀喇沁旗| 交口县| 舒城县| 鹤山市| 抚顺县| 芒康县| 鄢陵县| 枝江市| 宁蒗| 竹溪县| 太谷县| 怀集县| 民丰县| 孟津县| 大兴区| 连云港市| 堆龙德庆县| 沙洋县| 台江县|