Wednesday 21 August 2013

Alloy - REST API Json to TableView

Hi,

I am creating simple application for fetching JSON data from REST API and display the data to Table View.

You can download the source code from json2tableview repository

Steps:


1. Create simple alloy Project
2. Modify index.xml

 

 
  
 



3. Modify index.js
function openDetail(e) {
 alert('row index = ' + JSON.stringify(e.index));
 //Ti.API.info('row rowData = ' + JSON.stringify(e.rowData));
 //Ti.API.info('row index = ' + JSON.stringify(e..index));
}

var data = [];

var sendit = Ti.Network.createHTTPClient({

 onerror : function(e) {

  Ti.API.debug(e.error);

  alert('There was an error during the connection');

 },

 timeout : 1000,

});

// Here you have to change it for your local ip

sendit.open('GET', 'https://maps.googleapis.com/maps/api/place/nearbysearch/json?types=hospital&location=13.01883,80.266113&radius=1000&sensor=false&key=AIzaSyDStAQQtoqnewuLdFwiT-FO0vtkeVx8Sks');

sendit.send();

// Function to be called upon a successful response

sendit.onload = function() {

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

 // var json = json.todo;

 // if the database is empty show an alert

 if (json.length == 0) {
  $.table.headerTitle = "The database row is empty";
 }

 // Emptying the data to refresh the view

 // Insert the JSON data to the table view
 var countries = json.results;
 for ( var i = 0, iLen = countries.length; i < iLen; i++) {

  data.push(Alloy.createController('row', {
   icon : countries[i].icon,
   name : countries[i].name

  }).getView());

  // data.push(row);

  Ti.API.info(countries[i].icon);
  Ti.API.info(countries[i].name);

 }

 $.table.setData(data);
};

$.index.open();

4. Create Alloy Controller row (it create row.xml, row.js, row.tss)
5. Modify row.xml
 

 
  >
  


6. Modify row.js
 
var args = arguments[0] || {};

$.icon.image = args.icon;
$.catID.text = ar

7. Add styles to tss files
index.tss
 
"Window":{
 backgroundColor :"#FFF",
 exitOnClose:true,
 navBarHidden:true
}


row.tss
 
"#icon":{
 left:0,
 height:50,
 width:50
}

"TableViewRow":{
 layout:"horizontal"
}

"Label":{
 color:'#000',
 font:{
  fontFamily:"Ariel",
  fontSize:'20dp',
  fontWeight:'bold'
 }
}



Thanks

No comments:

Post a Comment