RibbonWind

Titanium ListView: Google Book API

Apr 5th, 2013
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var API_URL = 'https://www.googleapis.com/books/v1/volumes?q=';
  2. var MAX_BOOKS = 100;
  3. var SEARCH_TERM = "Harry Potter";
  4.  
  5. var win = Ti.UI.createWindow({
  6.     backgroundColor : "#FFF"
  7. });
  8.  
  9. var section = Ti.UI.createListSection();
  10. var listView = Ti.UI.createListView({
  11.     sections : [section]
  12. });
  13. win.add(listView);
  14. win.open();
  15.  
  16. function processBookData(data) {
  17.     var books = [];
  18.  
  19.     // make sure the returned data is valid
  20.     try {
  21.         var items = JSON.parse(data).items;
  22.     } catch (e) {
  23.         alert('Invalid response from server. Try again.');
  24.         return;
  25.     }
  26.  
  27.     // process each book, appending it to the list view
  28.     for (var i = 0; i < Math.min(items.length, MAX_BOOKS); i++) {
  29.         var info = items[i].volumeInfo;
  30.         if (!info) {
  31.             continue;
  32.         }
  33.         books.push({
  34.             properties : {
  35.                 title : info.title
  36.             }
  37.         });
  38.     }
  39.     section.setItems(books);
  40. }
  41.  
  42. function searchForBooks() {
  43.     // validate search data
  44.     var value = encodeURIComponent(SEARCH_TERM);
  45.    
  46.     // search Google Book API
  47.     var xhr = Ti.Network.createHTTPClient({
  48.         onload : function(e) {
  49.             processBookData(this.responseText);
  50.         },
  51.         onerror : function(e) {
  52.             alert('There was an error processing your search. Make sure you have a network connection and try again.');
  53.             Ti.API.error('[ERROR] ' + (e.error || JSON.stringify(e)));
  54.         },
  55.         timeout : 5000
  56.     });
  57.     xhr.open("GET", API_URL + value);
  58.     xhr.send();
  59. }
  60.  
  61. searchForBooks();
Add Comment
Please, Sign In to add comment