Titanium:Getting Nothing in when trying to access json data from remote server - titanium

I have a json data in my remote server,and i want to show it in table view,here is my json data
[{"offerType":"Discount","offerName":"BURBERRY - Buy 2 get 1 free on men's leather coat collectioN"},{"offerType":"Discount","offerName":"ARMANI JUNIOR- 20% off on Purchase worth INR 30000"}]
var url = "http://203.122.12.58:8080/api? username=superuser&password=superuser&action=invokeService&serviceName=offerAction&methodNa me=getMyOffers&customerId=CUS-12220&storeId=CMPNY-3376";
var win = Ti.UI.createWindow();
win = Ti.UI.currentWindow;
win.setBackgroundColor('gray');
//win.setBackgroundColor = 'white';
var table = Ti.UI.createTableView();
var tableData = [];
var json, fighters, fighter, i, row, nameLabel, nickLabel,offerType,offerName;
var xhr = Ti.Network.createHTTPClient({
onload: function() {
// Ti.API.debug(this.responseText);
json = JSON.parse(this.responseText);
for (i = 0; i < json.length; i++) {
console.log("json = %d",i);
offerType = json[i].offerType;
row = Ti.UI.createTableViewRow({
height:'60dp'
});
nameLabel = Ti.UI.createLabel({
text:offerType,
font:{
fontSize:'24dp',
fontWeight:'bold'
},
height:'auto',
left:'10dp',
top:'5dp',
color:'#000',
touchEnabled:false
});
offerName = json[i].offerName;
nickLabel = Ti.UI.createLabel({
text:'"' + fighter.nickname + '"',
font:{
fontSize:'16dp'
},
height:'auto',
left:'15dp',
bottom:'5dp',
color:'#000',
touchEnabled:false
});
row.add(nameLabel);
row.add(nickLabel);
tableData.push(row);
}
table.setData(tableData);
},
onerror: function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
alert('There was an error retrieving the remote data. Try again.');
},
timeout:5000
});
xhr.open("GET", url);
xhr.send();
how can i achieve my goal,Thanks in advance.
Akshay

Your code was pretty close. I did make a few changes so you'll have to compare them to see how to fix it. This example reads your service and displays the 2 entries in a table.
See the comments in the code detailing how it was changed.
//**** Not sure if this is an issue with formating on Stackoverflow or copy and paste, but the spaces in the URL are causing an issue.****
//var url = "http://203.122.12.58:8080/api? username=superuser&password=superuser&action=invokeService&serviceName=offerAction&methodNa me=getMyOffers&customerId=CUS-12220&storeId=CMPNY-3376";
var url = "http://203.122.12.58:8080/api?username=superuser&password=superuser&action=invokeService&serviceName=offerAction&methodName=getMyOffers&customerId=CUS-12220&storeId=CMPNY-3376";
var win = Ti.UI.createWindow();
//*****If you are calling this from another window, you may need this is your overall code, but my example I removed it.*****
//win = Ti.UI.currentWindow;
win.setBackgroundColor('gray');
//win.setBackgroundColor = 'white';
var table = Ti.UI.createTableView();
var tableData = [];
// **** Removed variable fighters because it is never used.
// **** Removed the fighter variable because it is never used.
var json, i, row, nameLabel, nickLabel, offerType, offerName;
var xhr = Ti.Network.createHTTPClient({
onload: function() {
// Ti.API.debug(this.responseText);
json = JSON.parse(this.responseText);
for (i = 0; i < json.length; i++) {
console.log("json = %d",i);
offerType = json[i].offerType;
row = Ti.UI.createTableViewRow({
height:'60dp'
});
nameLabel = Ti.UI.createLabel({
text: offerType,
font:{
fontSize:'24dp',
fontWeight:'bold'
},
height:'auto',
left:'10dp',
top:'5dp',
color:'#000',
touchEnabled:false
});
offerName = json[i].offerName;
nickLabel = Ti.UI.createLabel({
//text:'"' + fighter.nickname + '"', ***** fighter.nickname isn't defined anywhere so it is giving an error. You defined offerName right above it so I assume that it
// was the intended variable here.
text: offerName,
font:{
fontSize:'16dp'
},
height:'auto',
left:'15dp',
bottom:'5dp',
color:'#000',
touchEnabled:false
});
row.add(nameLabel);
row.add(nickLabel);
tableData.push(row);
}
table.setData(tableData);
},
onerror: function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
alert('There was an error retrieving the remote data. Try again.');
},
timeout:5000
});
xhr.open("GET", url);
xhr.send();
// Thought this might just be a test application, the table was never added to the window, so it would never be displayed so we can see the data. This is how you add the table.
win.add(table);
// I added code here to OPEN the window so I could see something displayed. Otherwise I just get the Appcelerator splash screen
win.open();

Related

Prebid not rendering winning bid

I was trying to setup prebid. I am able to receive bids, however the winning bid is not picked or the respective line item is not triggered, the ad of the bidder is not displayed. Instead it goes back to a fallback line items I created for $0.00 . The prebid console stops at Attempting to set key value for slot XXXX and then nothing, no winners, no render ad as shown in the below link
Look at the following image
Here hb_pb value is 0.40. But the respective line item is not selected even though there are line items with hb_pb of 0.36, 0.39 etc.
In the delivery diagnostics, I don't see the hb_pb request going to dfp. I am not sure why the case is. Please check the image. Here is my prebid code.
var PREBID_TIMEOUT = 1000;
var adUnits = [{
code: 'XXXX',
sizes: [
[300, 250]
],
bids: [{
bidder: 'XXXX',
params: {
id: YYYYY
}
}, {
bidder: 'XXXXX',
params: {
placementId: 'YYYYY'
}
}]
}];
var pbjs = pbjs || {};
pbjs.que = pbjs.que || [];
var googletag = googletag || {};
googletag.cmd = googletag.cmd || [];
googletag.cmd.push(function() {
googletag.pubads().disableInitialLoad();
});
pbjs.que.push(function() {
pbjs.aliasBidder('XXX', 'YYY');
pbjs.addAdUnits(adUnits);
pbjs.requestBids({
bidsBackHandler: sendAdserverRequest
});
});
function sendAdserverRequest() {
if (pbjs.adserverRequestSent) return;
pbjs.adserverRequestSent = true;
googletag.cmd.push(function() {
pbjs.que.push(function() {
pbjs.setTargetingForGPTAsync();
googletag.pubads().refresh();
});
});
}
setTimeout(function() {
sendAdserverRequest();
}, PREBID_TIMEOUT);
(function() {
var gads = document.createElement('script');
gads.async = true;
gads.type = 'text/javascript';
var useSSL = 'https:' == document.location.protocol;
gads.src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
var node = document.getElementsByTagName('script')[0];
node.parentNode.insertBefore(gads, node);
})();
googletag.cmd.push(function() {
googletag.defineSlot('/XXXXX/YYYY, [300, 250], 'XXXXXXX').addService(googletag.pubads());
googletag.pubads().enableSingleRequest();
googletag.enableServices();
});
Issue here is that DFP is rendering the ad before prebid sets the key values OR something in your code is overwriting prebid key values
(DFPs setTargetting overwrites anything that's already on a slot)
I’d verify that you have DFPs disableInitalLoad set, and/or recall pbjs.setTargetingForGPTAsyc() just before your googletag.pubads().refresh()’s

Google Places API - Getting Phone Number and Website

I believe I need to make follow up calls to get the results I am looking for. However, I cannot get the phone number and www url for any of the results I pull up.
I am a novice and need some help explaining where in this code I can get the correct results pulled. Please see the demo site here:
http://news.yeselectric.com/gmaps-excel-master/
Here is my JS code:
var store = (function () {
var searchBox,
infowindow,
markers = [],
myLatlng = new google.maps.LatLng(50.0019, 10.1419),
myOptions = { zoom: 6, center: myLatlng, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false, streetViewControl:false },
customIcons = { iconblue: './icons/blue.png' };
var init = function() {
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
input = (document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
searchBox = new google.maps.places.SearchBox((input));
store.listener();
},
listener = function() {
google.maps.event.addListener(searchBox, 'places_changed', function() {
//search for places
var places = searchBox.getPlaces();
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
//set markers zero
markers = [];
$('.addaddress').empty();
//get new bounds
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
store.create_marker(place);
//append to the table
$('.addaddress').append('<tr><td>'+ place.name +'</td><td>'+ place.formatted_address +'</td><td>'+ place.formatted_phone_number +'</td><td>'+ place.website +'</td></tr>');
bounds.extend(place.geometry.location);
}
//set the map
map.fitBounds(bounds);
});
},
create_marker = function(info) {
//create a marker for each place
var marker = new google.maps.Marker({ map: map, icon: customIcons.iconblue, title: info.name, position: info.geometry.location });
//infowindow setup
google.maps.event.addListener(marker, "click", function() {
if (infowindow) {
infowindow.close();
}
infowindow = new google.maps.InfoWindow({content: info.name});
infowindow.open(map, marker);
});
//push the marker
markers.push(marker);
}
return {
init: init,
listener: listener,
create_marker: create_marker
};
})();
google.maps.event.addDomListener(window, 'load', store.init);
Google's API returns different place metadata, depending on which call you're using. To get more place details, you'll need to get the place's placeId and use that to make a call to place.getDetails()
Here's a more thorough answer: https://stackoverflow.com/a/9523345/2141296

Opening a new window on a tableview row click in titanium

I am trying to open a new window by click a row in tableview in titanium.
this is my code,
function listpage(){
var tabgroup=Ti.UI.createTabGroup();
var win = Ti.UI.createWindow({
title:'Listpage',
backgroundColor:'#fff'
});
var dataArray = [{
title:'Sunday',
hasChild:true,
test:'detail'}];
for(var i=0;i<dataArray.length;i++){
dataArray[i].color = '#000';
dataArray[i].font = {fontWeight:'bold',fontSize:20};
}
var tableview=Ti.UI.createTableView({
data:dataArray
});
tableview.addEventListener('click',function(e){
if(e.rowData){
Ti.API.info(e.rowData.title);
var winEvent = Titanium.UI.createWindow({
backgroundColor:'#fff',
url:e.rowData.test
});
winEvent.open({animation:true});
}
});
win.add(tableview);
win.open();
}
detail.js code :
var self = Ti.UI.createWindow({
title:'Detail',
color:'#000',
backgroundColor:'white'
});
var label = Ti.UI.createLabel({
text:'Hai',
color:'#000'
});
self.add(label);
What to do to open detail.js window by clicking tableview row.
Thankyou.
Surendra, this is something similar to your problem. It opens a window while you clicks on each row.
Code is
var wndHome = Ti.UI.createWindow({
backgroundColor : 'white'
});
var tableView = Ti.UI.createTableView({
top : 0
});
var tabledata = [];
for(var i = 0 ; i < 10; i++){
var row = Ti.UI.createTableViewRow({
title : 'Title of window',
url : 'details.js'
});
tabledata.push(row);
}
tableView.data = tabledata;
wndHome.add(tableView);
wndHome.open();
tableView.addEventListener('click', function(e){
var wndNewWindow = Ti.UI.createWindow({
backgroundColor : '#999966',
url : e.rowData.url
});
wndNewWindow.open();
});
details.js file
var self = Ti.UI.currentWindow;
var label = Ti.UI.createLabel({
text:'Hai',
color:'#000'
});
self.add(label);
Here I've given the url to details.js. If you want to use different windows, then keep the file names in an array and while creating the tableViewRow, you can simply add the array element as the url(eg: fileArray = ['file1.js', 'file2.js','file3.js'];).
Try this and change your code as per your requirement.

titanium TableRows are not inserted

i'm getting a JSON response properly but my problem is with showing it. what's wrong with my code.
// this sets the background color of the master UIView (when there are no windows/tab groups on it)
Titanium.UI.setBackgroundColor('#000');
// create base UI tab and root window
var win1 = Titanium.UI.createWindow({
title : 'Main Window',
backgroundColor : '#fff'
});
var listUrl = "http://magadhena.com/test/list.php?FCODE=5&USERID=1";
var NumberOfLists = [];
var lists;
var tableData = [];
var table = Ti.UI.createTableView({
top : 40,
left : 10,
width : 300
});
var txt1 = Titanium.UI.createTextField({
top : 10,
left : 10,
width : 250
});
var button1 = Ti.UI.createButton({
top : 10,
left : 270,
width : 30
});
var xhr = Ti.Network.createHTTPClient();
xhr.setTimeout(3000);
xhr.onload = function() {
lists = eval('(' + this.responseText + ')');
for(var i = 0; i < lists.length; i++) {
var userId = lists[i].userid;
// The userID
var listId = lists[i].listid;
// The ListID
var listName = lists[i].listname;
// The ListName
var Object1 = new list(userId, listId, listName);
// Ti.API.log("Object is ",Object1.listId);
NumberOfLists.push(Object1);
// Ti.API.log("the size of the Json array is" , NumberOfLists.length);
}
};
xhr.open("GET", listUrl);
xhr.send();
for(var i = 0; i < NumberOfLists.length; i++) {
var row = Ti.UI.createTableViewRow({
title : NumberOfLists[i].listName
});
Ti.API.log("populating the data table ", NumberOfLists[i].toString);
tableData.push(row)
};
// Ti.API.log("the size of table data is ", tableData.length);
table.setData(tableData);
win1.add(table);
win1.add(txt1);
win1.add(button1);
// Opening Window1
win1.open();
///// List Objects
function list(userid, listid, listname) {
this.userId = userid;
this.listId = listid;
this.listName = listname;
}
You need to put table.setData() into xhr.onload function. Since you defined the code outside of the function, NumberOfLists is empty until xhr.onload function executed

After Refresh dont append the same data

im using for first time appcelerator for a Iphone app, im using a TableViewRow, when the window load all is fine, but if i want to refresh the window, the TableViewRow repeat the same data every time that i push refresh, so, i have 5 Categories, after refresh im having the same Categories repeting every time that im trying to refresh.
Ti.UI.backgroundColor = '#dddddd';
var url = "http://remoteJSON.js";
var win = Titanium.UI.currentWindow;
var table = Titanium.UI.createTableView();
var tableData = [];
var json, categorias, categoria, i, row, categoriaLabel, descripcionLabel;
var refreshBtn = Titanium.UI.createButton({
systemButton: Ti.UI.iPhone.SystemButton.REFRESH
});
refreshBtn.addEventListener('click', function() {
loadTutoriales();
});
win.setRightNavButton(refreshBtn);
var actInd = Titanium.UI.createActivityIndicator({
bottom:10,
height:50,
width:10,
style:Titanium.UI.iPhone.ActivityIndicatorStyle.PLAIN
});
function loadTutoriales(){
if(!Titanium.Network.online){
alert("Debe conectarse a internet.");
}
var xhr = Ti.Network.createHTTPClient({
onload: function() {
actInd.show();
actInd.message = 'Loading...';
//Ti.API.debug(this.responseText);
json = JSON.parse(this.responseText);
for (i = 0; i < json.categorias.length; i++) {
var rowColor = '#eeeeee';
if(i & 1){
rowColor = '#ffffff';
}
categoria = json.categorias[i];
var row = Ti.UI.createTableViewRow({
height:'auto',
hasChild:true
});
row.backgroundColor=rowColor;
/* add */
var post_view = Titanium.UI.createView({
height:'auto',
layout:'vertical',
top:5,
right:5,
bottom:5,
left:5
});
var av_image = Titanium.UI.createImageView({
image:categoria.imageUrl,
top:0,
left:0,
height:48,
width:48
});
post_view.add(av_image);
var inner_view = Titanium.UI.createView({
height:'auto',
layout:'vertical',
top:0,
right:0,
bottom:0,
left:0
});
/* end add */
var categoriaLabel = Ti.UI.createLabel({
text:categoria.categoryName,
left:54,
width:120,
top:-48,
bottom:0,
height:18,
textAlign:'left',
color:'#444444',
font:{fontFamily:'Trebuchet MS',fontSize:14,fontWeight:'bold'}
});
inner_view.add(categoriaLabel);
var descripcionLabel = Ti.UI.createLabel({
text:'"' + categoria.description + '"',
left:54,
top:0,
bottom:2,
height:'auto',
width:'auto',
textAlign:'left',
font:{fontSize:14}
});
inner_view.add(descripcionLabel);
post_view.add(inner_view);
row.add(post_view);
//row.add(descripcionLabel);
tableData.push(row);
}
table.setData(tableData);
},
onerror: function(e) {
Ti.API.debug("STATUS: " + this.status);
Ti.API.debug("TEXT: " + this.responseText);
Ti.API.debug("ERROR: " + e.error);
alert('There was an error retrieving the remote data. Try again.');
},
timeout:5000
});
//win.add(actInd);
win.add(table);
win.open();
//actInd.hide();
xhr.open("GET", url);
xhr.send();
}
loadTutoriales();
When you press the refresh button clear the tableData array and assign to table set data function before you fill your table again. So it will empty your table first and than fill new refreshed data.
Like this,
refreshBtn.addEventListener('click', function() {
tableData = [];
table.setData(tableData);
loadTutoriales();
});