Searching and retrieving data via Yahoo! YQL

YQL is an SQL-like language that allows you to query, filter, and combine data from multiple sources across both the Yahoo! Network and other open data sources. Normally, developer access to data from multiple resources is disparate and requires calls to multiple APIs from different providers, often with varying feed formats. YQL eliminates this problem by providing a single endpoint to query and shape the data you request. You may remember that we briefly touched on the usage of YQL via standard HTTP Request calls in Chapter 2, however, in this chapter, we will be utilizing the built-in Titanium YQL methods.

Titanium has built-in support for YQL, and in this recipe we will create a simple application that searches for stock data on the YQL network, and then displays that data in a simple label.

Note

Note that when using YQL in an un-authenticated manner (such as we are doing here), there is a usage limit imposed of 100,000 calls per day. For most applications, this is a more than generous limit. However, if you do wish to have it increased, you will need to authenticate your calls via OAuth. You can do this by signing up with Yahoo! and registering your application.

The complete source code for this recipe can be found in the /Chapter 9/Recipe 5 folder.

How to do it…

Create a new project, and then open the app.js file, removing any existing content. Now type in the following code:

//
// create base UI tab and root window
//
var win1 = Titanium.UI.createWindow({  
    backgroundColor:'#fff'
});

// This is the input textfield for our stock code
var txtStockCode = Titanium.UI.createTextField({
    hintText: 'Stock code, e.g. APPL',
    borderWidth: 0,
    width: 200,
    left: 10,
    height: 30,
    font: {fontSize: 14, fontColor: '#262626'},
    autoCorrect: false,
    autocapitalization: Titanium.UI.TEXT_AUTOCAPITALIZATION_ALL,
    borderStyle: 1,
    top: 5
});

//add the text field to the window
win1.add(txtStockCode);

// Create the search button from our search.png image  
var btnSearch = Titanium.UI.createButton({  
    title: 'Search YQL', 
    width: 80,  
    height: 30,  
    right: 10,  
    borderRadius: 3,
    top: 5  
});  

//add the button to the window
win1.add(btnSearch);  

//This function is called on search button tap
//it will query YQL for our stock data
function searchYQL() {

  // Do some basic validation to ensure the user 
  //has entered a stock code value
  if(txtStockCode.value != '')
  {
    txtStockCode.blur(); //hides the keyboard

    // Create the query string using a combination of 
    //YQL syntax and the value of the txtStockCode field
    var query = 'select * from yahoo.finance.quotes where symbol 
                 = "' + txtStockCode.value + '"';

    // Execute the query and get the results
    Titanium.Yahoo.yql(query, function(e) {
        var data = e.data;
        //Iff ErrorIndicationreturnedforsymbolchangedinvalid 
        //is null then we found a valid stock
            
     if(data.quote.ErrorIndicationreturnedforsymbolchangedinvalid 
      == null)
     {
         //show our results in the console
         Ti.API.info(data);
       
        var lblStockInfo = Titanium.UI.createLabel({
            top: 60,
            left: 20,
            width: 280,
            height: 'auto',
            text: ''
          });
          
          //create a label to show some of our info
          lblStockInfo.text = lblStockInfo.text 
           + 'Company name: ' + data.quote.Name;  
          lblStockInfo.text = lblStockInfo.text +'
Days Low: ' 
           + data.quote.DaysLow; 
          lblStockInfo.text = lblStockInfo.text +'
Days High: ' 
           + data.quote.DaysHigh; 
          lblStockInfo.text = lblStockInfo.text +'
Last Open: ' 
           + data.quote.Open; 
          lblStockInfo.text = lblStockInfo.text +'
Last Close: ' 
           + data.quote.PreviousClose; 
          lblStockInfo.text = lblStockInfo.text +'
Volume: ' 
           + data.quote.Volume; 
          
          win1.add(lblStockInfo);
     
     }
        else
        {
            //show an alert dialog saying nothing could be found
            alert('No stock information could be found for ' + txtStockCode.value);
        }
    });
    
  } //end if
}


// Add the event listener for this button  
btnSearch.addEventListener('click', searchYQL);  


//open the window
win1.open();

You should now be able to run the app in your emulator and search for a stock symbol (such as 'AAPL' for Apple Inc.), and have some of the results listed out to a label on the screen, as seen next:

How to do it…

How it works…

What is actually going on here within the searchYQL() function? First, we're doing a very basic validation on the text field to ensure the user has entered in a stock symbol before pressing search. If a stock symbol is found, we use the blur() method of the text field to ensure the keyboard becomes hidden. The meat of the code revolves around creating a Yahoo! YQL query using the correct syntax and providing the text field value as the symbol parameter. This YQL query is simply a string, joined together using the + symbol, much like you would do with any other string manipulation in JavaScript.

We then execute our query using the Titanium.Yahoo.yql() method, which returns the results within the 'e' object of the inline response function. We can then manipulate and use this JSON data in any way we wish. In this case, we're assigning a subsection of it to a label on the screen so the user can view the daily opening and closing figures of the stock in question.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.95.245