I am trying to create a single column picker whose data is derived from a json doc. Right now i am coding for an iOS device, but plan to use same code for android. When i run this code, the picker is empty. Any help is appreciated!
////
var win = Titanium.UI.createWindow({
title:"Creating a Single-Column Picker",
backgroundColor:"#FFF",
exitOnClose:true
});
var url ="http://stats.catchitkansas.com/sunflower/cik/xml/app/app_master_schools.json"; // rss feed url
var json, object_name, locatie, i, row, title, val;
//A single column picker
var picker = Ti.UI.createPicker({
bottom:0,
});
var xhr = Ti.Network.createHTTPClient({
onload: function(e) { // Ti.API.debug(this.responseText);
json = JSON.parse(this.responseText);
for (i = 0; i < json.object_name.length; i++) {
locatie = json.object_name[i];
picker.add(Ti.UI.createPickerRow({title: e.locatie.title}));
}
//Now, we need add the pickerRow objects in the data array to the picker
Ti.API.debug(this.responseText);
alert('success');
},
}
);
picker.selectionIndicator = true;
xhr.open('GET',url);
xhr.send();
//This label contains text that will change with each picker change
var results = Titanium.UI.createLabel({
text:"Select from the picker below",
height:40,
width:"auto",
top:20
});
//When using a picker, listen for the "change" event
picker.addEventListener("change", function(e){
results.text = e.row.title + ": " + e.row.val; //Pull the title and val properties from the selected pickerRow object (accessed via e.row)
});
win.add(picker);
win.add(results);
win.open();
Issue #1
Your data feed is returning improperly formatted JSON.
Change this
"object_name": {to
"object_name":(Found by running the JSON through http://jsonlint.com/)
Issue #2
Change this
picker.add(Ti.UI.createPickerRow({title: e.locatie.title}));to
picker.add(Ti.UI.createPickerRow({title: locatie.title}));The
locatieobject isn’t part of the event variablee, it’s a stand-alone variable.Issue #3
The picker is being added before the HttpClient request is finished.
You should move
win.add(picker);to just after theforloop inside theonloadcallback.