Titanium Community Questions & Answer Archive

We felt that 6+ years of knowledge should not die so this is the Titanium Community Questions & Answer Archive

Parse json data to tableView

Hey everyone,

I am writing an app that tracks your recent games on Halo Reach, using Bungie.net's API.

I am having trouble parsing json data, i think it may be invalid json but would appreciate a second opinion on my code, (plus any ways i can optimise it).

here's the json data i'm using…

http://pastie.org/1190185

and here's my code to grab and loop through data (namely MapName value in this instance) and push this into a table view (please note where {apiKey} is my private API key).


var gameHistoryWindow = Ti.UI.currentWindow;

// set up tableView
var tableView = Ti.UI.createTableView({  
    backgroundColor: 'transparent',
    separatorStyle: Ti.UI.iPhone.TableViewSeparatorStyle.NONE,
    style: Ti.UI.iPhone.TableViewStyle.UNGROUPED
});

gameHistoryWindow.add(tableView);


// fetch list of recent games
function fetchRecentGames(){ 

    // Empty array "data" for our tableview
    var data = [];


    // fetch list of recent games
    var fetchGameHistory = Ti.Network.createHTTPClient();

    // set timeout
    fetchGameHistory.setTimeout(10000);

    // catch errors
    fetchGameHistory.onerror = function(e) { 
        alert('error getting games');
    };

    // open connection
    fetchGameHistory.open('GET','http://www.bungie.net/api/reach/reachapijson.svc/player/gamehistory/{apiKey}/Cheeky%20Squeezes/unknown/0');

    // Send the HTTP request
    fetchGameHistory.send();

    // act on response
    fetchGameHistory.onload = function(){

        var games = JSON.parse(this.responseText);        

            for (var i=0; i<games.rows; i++){

                var row = Ti.UI.createTableViewRow({
                    height:30,
                    title:games[i].RecentGames.MapName
                });

            // apply rows to data array
            data.push(row);

            };

    // set data into tableView
    tableView.setData(data);

    };


}

fetchRecentGames();

When the code is run in the iPhone emulator i get this info in the Titanium Info pane..


[WARN] Exception in event callback. {
line = 44;
message = "Unable to parse JSON string";
name = SyntaxError;
sourceId = 239046352;
sourceURL = "file://Resources/gameHistory.js";
}

Is this definitely an incorrect json formatting issue or have i missed something? i have tried replacing the "JSON.parse(this.responseText);" bit with
"eval('('+this.responseText+')');" but no success there either, same error thrown either way.

appreciate any input people, thanks, (keep up the good work Appcelerator team, blown away by how awesome this is!!!)

Aaron :)

— asked September 29th 2010 by Aaron Bentley
  • iphone
  • json.parse
  • mobile
0 Comments

4 Answers

  • This is great! I was about to start a Halo Reach app! One thing that you might want to try is putting your fetchGameHistory.send and fetchGameHistory.open lines below your fetchGameHistory.onload callback.

    — answered September 30th 2010 by Andrew Scofield
    permalink
    0 Comments
  • Try this:
    // fetch list of recent games
    function fetchRecentGames(){

    // Empty array "data" for our tableview
    var data = [];
    
    
    // fetch list of recent games
    var fetchGameHistory = Ti.Network.createHTTPClient();
    
    // set timeout
    //fetchGameHistory.setTimeout(10000);
    fetchGameHistory.timeout = 10000;
    
    // catch errors
    fetchGameHistory.onerror = function(e) { 
        alert('error getting games');
        Ti.API.info(e); 
    };
    
    
    // open connection
    fetchGameHistory.open('GET','http://www.bungie.net/api/reach/reachapijson.svc/player/gamehistory/{apiKey}/Cheeky%20Squeezes/unknown/0');
    
    
    // act on response
    fetchGameHistory.onload = function(){
    
        //var games = JSON.parse(this.responseText);      
        var games = eval('('+this.responseText+')');
            for (var i=0; i<games.length; i++){
    
                var row = Ti.UI.createTableViewRow({
                    height:30,
                    title:games[i].RecentGames.MapName
                });
    
            // apply rows to data array
            data.push(row);
    
            };
    
    // set data into tableView
    tableView.setData(data);
    
    };
    
    // Send the HTTP request
    fetchGameHistory.send();
    

    }

    fetchRecentGames();

    — answered September 30th 2010 by Varun Atluri
    permalink
    1 Comment
    • Hey Varun,
      thx for this, the function is calling the api, but no data is being added to the table view, i have also re-arranged as Andrew recommended above. ANy ideas? i think i have gained a few grey hairs trying to get this working :S

      — commented October 2nd 2010 by Aaron Bentley
  • Sorry doble post

    — answered April 5th 2011 by Bruno Coelho
    permalink
    0 Comments
  • I got exactly the same problem. In android works, but not on iphone. Have you solve the problem?

    cumps

    — answered April 5th 2011 by Bruno Coelho
    permalink
    1 Comment
    • Hi Bruno :)
      i haven't worked on this code in a while, but this was the end product that works (using titanium sdk 1.4.2 & iOS sdk 4.0 {apologies as i do not have the ability to test in Android on this system}).

      
      // fetch list of recent games 
      function fetchRecentGames(e){
      
          var gamertag = fetchGamertag();
      
          // fetch list of recent games
          var fetchGameHistory = Ti.Network.createHTTPClient();
      
          // set timeout
          fetchGameHistory.timeout = 10000;
      
          // catch errors
          fetchGameHistory.onerror = function(e) {
              alert('error getting games');
              Ti.API.info(e); 
          };
      
          // act on response
          fetchGameHistory.onload = function(e){
      
              var gamesList = JSON.parse(this.responseText);
      
              // Empty array data for our tableview
              var data = [];
      
                  for (var i=0; i<gamesList.RecentGames.length; i++){
      
                      var rows = Ti.UI.createTableViewRow({
      
                              title: gamesList.RecentGames[i].MapName,
                              gameID: gamesList.RecentGames[i].GameId,                
                              color:'#fff',
                              shadowColor:'#333',
                              shadowOffset:{x:1,y:1},
                              hasChild:true
                      });        
      
                      // apply rows to data array
                      data.push(rows);
      
                  };
      
                  // set data into tableView
                  gameHistoryMenu.setData(data, {animationStyle:Ti.UI.iPhone.RowAnimationStyle.FADE});
      
          };
      
          // open connection
          fetchGameHistory.open('GET','http://www.bungie.net/api/reach/reachapijson.svc/player/gamehistory/' + apiKey + '/' + gamertag + '/unknown/0');
      
          fetchGameHistory.setRequestHeader('Content-Type','application/json');
      
          // Send the HTTP request
          fetchGameHistory.send();
      
      }
      

      Hope this helps :)

      — commented April 5th 2011 by Aaron Bentley
The ownership of individual contributions to this community generated content is retained by the authors of their contributions.
All trademarks remain the property of the respective owner.