titanium mobile:onload function called issue in json parsing - titanium-mobile

Hello friends,
I am developing an app in Titanium Studio sdk 1.8.1 using Google Place API to display category atm list & address in tableview so I use json parsing using this link but loader.onload function of getData method is not called immediately after send function of getData method in json parsing so its called after getDetailsData() function and also can't display address in tableview so please give me idea how to solve it.
Thanks in advance.
var lat ,lon ,radius , name , sensor , key , reference, address;
lat = '-33.8670522';//'23.042067';
lon = '151.1957362';//'72.530835';//
radius = '500';
name = title;
sensor = 'false';
key = 'AIzaSyDALrXHC4uMtfSrpCg6NHxqPhsLccLYPZE';
var rowData = [];
// getCategoryData using Google Place API
function getData()
{
var loader = Titanium.Network.createHTTPClient();
var url = "https://maps.googleapis.com/maps/api/place/search/json?";
url = url + "location=" + lat + ',' + lon;
url = url + "&radius=" + radius;
url = url + "&name=" + name;
url = url + "&sensor=" + sensor;
url = url + "&key=" + key;
Ti.API.info(url);
// Sets the HTTP request method, and the URL to get data from
loader.open("GET",url);
// Create our HTTP Client and name it "loader"
// Runs the function when the data is ready for us to process
loader.onload = function()
{
var obj = JSON.parse(this.responseText);
Ti.API.log(obj);
var results = obj.results;
Ti.API.log(results);
for (var i = 0; i < results.length; i++)
{
var name = obj.results[i].name;
reference = obj.results[i].reference;
Ti.API.log('Refernce:'+reference);
getDetailsData();
// Create a row and set its height to auto
var row = Titanium.UI.createTableViewRow({height:'auto'});
// Create the view that will contain the text and avatar
var post_view = Titanium.UI.createView({
height:'auto',
layout:'vertical',
top:5,
right:5,
bottom:5,
left:5
});
// Create the label to hold the tweet message
var nameLabel = Titanium.UI.createLabel({
//text:name,
left:30,
top:0,
bottom:2,
height:'auto',
width:236,
textAlign:'left',
font:{fontSize:14}
});
// Create the label to hold the tweet message
var addressLabel = Titanium.UI.createLabel({
text:'Address',
left:30,
top:0,
bottom:2,
height:'auto',
width:236,
textAlign:'left',
font:{fontSize:14}
});
nameLabel.text = name;
//addressLabel.text = placeAddress;
post_view.add(nameLabel);
post_view.add(addressLabel);
// Add the post view to the row
row.add(post_view);
// Give each row a class name
//row.className = "item"+i;
// Add row to the rowData array
rowData[i] = row;
//rowData.push(row);
}
//tableView.setData(rowData);
// Create the table view and set its data source to "rowData" array
var tableView = Titanium.UI.createTableView({data:rowData});
//Add the table view to the window
showWin.add(tableView);
};
//-- Network error
loader.onerror = function(e)
{
Ti.API.info('Network error: ' + JSON.stringify(e));
};
// Send the HTTP request
loader.send();
}
function getDetailsData ()
{
var loader1 = Titanium.Network.createHTTPClient();
Ti.API.log('getDetailsData');
var url = "https://maps.googleapis.com/maps/api/place/details/json?";
url = url + "reference=" + reference;
url = url + "&sensor=" + sensor;
url = url + "&key=" + key;
Ti.API.info(url);
// Sets the HTTP request method, and the URL to get data from
loader1.open("GET",url);
// Runs the function when the data is ready for us to process
loader1.onload = function()
{
var detailsObj = JSON.parse(this.responseText);
Ti.API.log(detailsObj);
address = detailsObj.result.formatted_address;
Ti.API.log('Address:'+address);
phoneno = detailsObj.result.formatted_phone_number;
Ti.API.log('Phone No:'+phoneno);
};
//-- Network error
loader1.onerror = function(event)
{
Ti.API.info('Network error: ' + JSON.stringify(event));
};
// Send the HTTP request
loader1.send();
return address;
}
getData();

Dont't use the return in the second http request.
Pass the label object in the function like:
getDetailsData(addressLabel);
and set the text inside loader1.onload like this:
address = detailsObj.result.formatted_address;
addressLabel.text = address;

Related

How to upload a image to Google Drive Shared folder and get its sharable URL?

currently I have a working Arduino App that takes a picture, uploads it to a Goggle Drive folder (already made public) and stores some related data on a Google Sheet including the image file name.
But I need to access this data and image from a web app running somewhere else.
The image name "filename.jpg" will not work as part of an URL.
In my current solution two scripts are used:
The first successfully transfers the image.
The second adds a line to the Google Sheet with all the necessary parameters but at this stage all I have is the filename.jpg.
I need to add something to the this second script to get filename.jpg's URL so it can be stored along with the related data on the Google Sheet.
If I could merge the functionality of both scripts in one it would do the job as the transfer script has access to the file ID but I really need help on this one.
Image transfer script:
function doPost(e) {
var myFoldername = e.parameter.myFoldername;
var myFile = e.parameter.myFile;
var myFilename = e.parameter.myFilename;
//var myFilename = Utilities.formatDate(new Date(), "GMT", "yyyyMMddHHmmss")+"-"+e.parameter.myFilename;
var myToken = e.parameter.myToken;
var contentType = myFile.substring(myFile.indexOf(":")+1, myFile.indexOf(";"));
var data = myFile.substring(myFile.indexOf(",")+1);
data = Utilities.base64Decode(data);
var blob = Utilities.newBlob(data, contentType, myFilename);
// Save a captured image to Google Drive.
var folder, folders = DriveApp.getFoldersByName(myFoldername);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(myFoldername);
}
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + myFilename);
var imageID = file.getUrl().substring(file.getUrl().indexOf("/d/")+3,file.getUrl().indexOf("view")-1);
var imageUrl = "https://drive.google.com/uc?authuser=0&id="+imageID;
// Send a link message to Line Notify.
var res = "Line Notify: ";
try {
var url = 'https://notify-api.line.me/api/notify';
var response = UrlFetchApp.fetch(url, {
'headers': {
'Authorization': 'Bearer ' + myToken,
},
'method': 'post',
'payload': {
'message': imageUrl
}
});
res += response.getContentText();
} catch(error) {
res += error;
}
return ContentService.createTextOutput(myFoldername+"/"+myFilename+"\n"+imageUrl+"\n"+res);
}
Google Sheet Script:
var timeZone = "UTC"; //get yours at https://www.timeanddate.com/time/zones/
var dateTimeFormat = "dd/MM/yyyy HH:mm";
var enableSendingEmails = true;
var emailAddress = ""; // comma separate for several emails
// 'bob#example.com';
// 'bob#example.com,admin#example.com';
function doGet(e) {
var result = 'Ok'; // default result
if (e.parameter == 'undefined') {
result = 'No Parameters';
} else {
var alarm= e.parameter.alarm;
if (typeof alarm != 'undefined') {
sendEmail("alarm text:" + stripQuotes(alarm));
return ContentService.createTextOutput(result);
}
var sheet = getSpreadSheet();
var lastRow = sheet.getLastRow();
var newRow = 1;
if (lastRow > 0) {
var lastVal = sheet.getRange(lastRow, 1).getValue();
//if there was no info for (sentEmailIfUnitIsOutForMinutes) checkIfDead() function will append row with 'dead' text
// so checking do we need to override it
if (lastVal == 'dead')
newRow = lastRow; //to overwrite "dead" value
else
newRow = lastRow + 1;
}
var rowData = [];
var namesOfParams=[];
for (var param in parseQuery(e.queryString))
namesOfParams.push(param);
// namesOfParams=namesOfParams.reverse();
//creatating headers if first row
if (newRow == 1) {
rowData[0] = "Date";
var i = 1;
for (var i=0; i<namesOfParams.length;i++ ) {
rowData[i+1] = namesOfParams[i];
}
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
rowData = [];
newRow++;
}
rowData[0] = Utilities.formatDate(new Date(), timeZone, dateTimeFormat);
for (var i=0; i<namesOfParams.length;i++ ) {
var value = stripQuotes(e.parameter[namesOfParams[i]]);
rowData[i+1] = value;
}
var newRange = sheet.getRange(newRow, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
// Return result of operation
return ContentService.createTextOutput(result);
}
// Remove leading and trailing single or double quotes
function stripQuotes(value) {
return value.replace(/^["']|['"]$/g, "");
}
function parseQuery(queryString) {
var query = {};
var pairs = (queryString[0] === '?' ? queryString.substr(1) : queryString).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
query[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1] || '');
}
return query;
}
function sendEmail(message) {
if (!enableSendingEmails)
return;
var subject = 'Something wrong with your esp';
MailApp.sendEmail(emailAddress, subject, message);
}
function getSpreadSheet() {
return SpreadsheetApp.getActiveSheet();
}
Assistance welcome.
Thanks
Paulo
Problem solved with the following script:
var timeZone = "GMT";
var dateTimeFormat = "dd/MM/yyyy HH:mm:ss";
var logSpreadSheetId = "1W1ypQEkfKNFSqhtfgbjbjFgzHO8LDaTv6mNWTP9h4M8";
// logSpreadSheetId is to be copied from the sheet's URL as follows: https://docs.google.com/spreadsheets/d/1W1ypQEkfKNFSqhtfgbjbjFgzHO8LDaTv6mNWTP9h4M8/edit#gid=0
function doPost(e) {
var myFoldername = e.parameter.myFoldername;
var myFile = e.parameter.myFile;
//var myFilename = e.parameter.myFilename;
//var myFilename = Utilities.formatDate(new Date(), timeZone, "ddMMyyyyHHmmss")+"-"+e.parameter.myFilename;
var myFilename = Utilities.formatDate(new Date(), timeZone, "ddMMyyyyHHmmss")+".jpg";
var myToken = e.parameter.myToken;
var contentType = myFile.substring(myFile.indexOf(":")+1, myFile.indexOf(";"));
var data = myFile.substring(myFile.indexOf(",")+1);
data = Utilities.base64Decode(data);
var blob = Utilities.newBlob(data, contentType, myFilename);
// Save a captured image to Google Drive.
var folder, folders = DriveApp.getFoldersByName(myFoldername);
if (folders.hasNext()) {
folder = folders.next();
} else {
folder = DriveApp.createFolder(myFoldername);
}
var file = folder.createFile(blob);
file.setDescription("Uploaded by " + myFilename);
var imageID = file.getUrl().substring(file.getUrl().indexOf("/d/")+3,file.getUrl().indexOf("view")-1);
var imageUrl = "https://drive.google.com/uc?authuser=0&id="+imageID;
addLog(myFilename,imageUrl);
return ContentService.createTextOutput(myFoldername+"/"+myFilename+"\n"+imageUrl+"\n"); //+res);
}
function addLog(myFilename,imageUrl) {
var spr = SpreadsheetApp.openById(logSpreadSheetId);
var sheet = spr.getSheets()[0];
var data = sheet.getDataRange().getValues();
var pos = sheet.getLastRow();
var rowData = [];
if(!pos>0){
pos = 1;
rowData[0] = "Date";
rowData[1] = "Image";
rowData[2] = "URL";
var newRange = sheet.getRange(pos, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
pos = pos +1;
rowData = [];
rowData[0] = Utilities.formatDate(new Date(), timeZone, dateTimeFormat);
rowData[1] = myFilename;
rowData[2] = imageUrl;
var newRange = sheet.getRange(pos, 1, 1, rowData.length);
newRange.setValues([rowData]);
}
Also, for simplicity, the sheet and the script now sit on independent files as the script can refer to the sheet using its ID as in: var logSpreadSheetId = "1W1ypQEkfKNFSqhtfgbjbjFgzHO8LDaTv6mNWTP9h4M8"; (Please used the ID of your own sheet).

There was an unexpected failure with this assessment, invalid type provided

I'm attempting to run the following code which is pretty much copied from the OoTheBox UI Action called "View User's Response".
function showRiskAssessment(){
var ra = new GlideRecord('asmt_assessment_instance');
ra.addQuery('task_id', '=', current.sys_id);
ra.orderByDesc('taken_on');
ra.setLimit(1);
ra.query();
// var id = g_form.getUniqueValue();
var id = ra.sys_id;
//var type = g_form.getValue('metric_type');
var type = '468aeff2db9357008aeba9f7059619ca';
var url = 'assessment_take2.do?sysparm_assessable_sysid=' + id + '&sysparm_assessable_type=' + type + '&sysparm_reader_view=true';
var d = new GlideOverlay({
title: "User's Response",
iframe: url,
width:'80%',
height: '100%',
onAfterLoad: function() {
var iframe = d.getIFrameElement();
setTimeout(function(){
iframe.height = parseInt(iframe.height)+1;
},0);
}
});
d.render();
}
If I hardcode it like this it works. All I'm trying to do is on the change record I want to look up the most recent Assessment Instance for that particular change and display in the overlay. Obviously I can't hardcode the id however it seems the query isn't recognizing that info at all anyways.
function showRiskAssessment(){
// var ra = new GlideRecord('asmt_assessment_instance');
// ra.addQuery('task_id', '=', current.sys_id);
// ra.orderByDesc('taken_on');
// ra.setLimit(1);
// ra.query();
// var id = g_form.getUniqueValue();
var id = '5c516eeddb87d090ebce60ab1396198a';
//var type = g_form.getValue('metric_type');
var type = '468aeff2db9357008aeba9f7059619ca';
var url = 'assessment_take2.do?sysparm_assessable_sysid=' + id + '&sysparm_assessable_type=' + type + '&sysparm_reader_view=true';
var d = new GlideOverlay({
title: "User's Response",
iframe: url,
width:'80%',
height: '100%',
onAfterLoad: function() {
var iframe = d.getIFrameElement();
setTimeout(function(){
iframe.height = parseInt(iframe.height)+1;
},0);
}
});
d.render();
}
You're trying to use current.sys_id in a client side script. It is recommended to use g_form for client side scripts. You're also trying a GlideRecord on a client script, which is also not recommended.
To fix, replace:
ra.addQuery('task_id', '=', current.sys_id);
with:
var sysId = g_form.getUniqueValue();
ra.addQuery('task_id', '=', sysId);
Also, for the difference between g_form and current have a look here.

How do I access every index of a specific Array inside an AJAX object

I'm calling an ajax for giphy, with this code:
$.ajax({
url: queryURL,
method: "GET"
}). then(function(response) {
console.log(response);
when I look at the console log there's an object with the first property being data. Each index of data is another object, inside this object are two properties i'm trying to pull, rating and url. I want to be able to list the rating and url not just of a specific index, but every index in that data array. What would be the best way to do that? Currently I've tried a for loop
for (var i = 0; i<response.data.length;i++){
var dataIndex = response.data[i];
}
then <creating a variable something like>
var imgURL = response.data[dataIndex].url
but its not working.
Here's the entire code
function displayTopicGif() {
var topic = $(this).attr("data-name");
// query url
var queryURL = "https://api.giphy.com/v1/gifs/search?q=" + topic + "&limit=20&rating=r&api_key=";
$.ajax({
url: queryURL,
method: "GET"
}).then(function (response) {
console.log(response);
// for loop to create a variable for the index of the objects data
for (var i = 0; i < response.data.length; i++) {
var dataIndex = response.data[i];
}
// where the gif's will be dumped
var topicDiv = $("<div class='topic'>");
// rating of gif
var rating = response.data[0].rating;
console.log(rating);
// Creating an element to have the rating displayed
var pOne = $("<p>").text("Rating: " + rating);
// add to the rating element
topicDiv.append(pOne);
// retrieve the IMG of the gif
var imgURL = response.data[0].url;
var image = $("<img>").attr("src", imgURL);
topicDiv.append(image);
// put gif into topic-view div
$("#topic-view").prepend(topicDiv);
});
}
You can check that something is an object using $.isPlainObject and then read through its properties via:
for (key in object) {
var value = object[key];
//log
}
Or you can get the keys using Object.getOwnPropertyNames();. See this sample excerpt from MDN:
const object1 = {
a: 1,
b: 2,
c: 3
};
console.log(Object.getOwnPropertyNames(object1));
// expected output: Array ["a", "b", "c"]

titanium mobile:get row value from tableview on button click issue

Hello friends,
I am developing an app using Google Place API in Titanium Development and successfully got data and display in tableview and add button in each row but my issue is that I want to get name and address on button click in each row so please give me idea or any link to solve my issue.
Please take a look in my screenshot so on btnclick I want to get name and address.
Thanks in advance.
var categoryName;
var addressLabel;
var row;
var tableData=[];
PlacesListCells = function createRow()
{
//var tableData=[];
var loader = Titanium.Network.createHTTPClient();
var url = "https://maps.googleapis.com/maps/api/place/search/json?";
url = url + "location=" + lat + ',' + lon;
url = url + "&radius=" + radius;
url = url + "&name=" + name;
url = url + "&sensor=" + sensor;
url = url + "&key=" + key;
Ti.API.info(url);
// Sets the HTTP request method, and the URL to get data from
loader.open("GET",url);
// Create our HTTP Client and name it "loader"
// Runs the function when the data is ready for us to process
loader.onload = function()
{
var obj = JSON.parse(this.responseText);
Ti.API.log(obj);
var results = obj.results;
Ti.API.log(results);
for (var i = 0; i < results.length; i++)
{
categoryName = obj.results[i].name;
reference = obj.results[i].reference;
Ti.API.log('Refernce:'+reference);
// Create a row and set its height to auto
row = Titanium.UI.createTableViewRow({height:'78'});
var placeImage = Titanium.UI.createImageView
({
image:'../iphone/appicon.png',
width:70,
height:50,
top:12,
left:5
});
// Create the label to hold the tweet message
var nameLabel = Titanium.UI.createLabel({
//text:name,
left:80,
top:5,
height:'auto',
width:185,
textAlign:'left',
font:{fontSize:12}
});
// Create the label to hold the tweet message
addressLabel = Titanium.UI.createLabel({
left:80,
top:25,
height:'auto',
width:185,
textAlign:'left',
font:{fontSize:14}
});
var arrowImage = Ti.UI.createImageView
({
image:'../iphone/appicon.png',
width:20,
height:20,
left:280,
top:30
});
var favoriteButton = Ti.UI.createButton
({
title:'btn',
//font:{fontFamily:'Helvetica Neue',fontSize:15},
top:20,
left:255,
height:30,
width:50,
url:'../Images/favorite.png'
//image:'../Images/favorite.png'
});
nameLabel.text = categoryName;
getDetailsData(addressLabel,row,i);
row.add(placeImage);
row.add(nameLabel);
row.add(addressLabel);
row.add(favoriteButton);
//row.add(arrowImage);
tableData[i] = row;
//set page title for each row
row.pageTitle = nameLabel.text;
favoriteButton.row = i;
favoriteButton.addEventListener('click', function(e)
{
Ti.API.log('favoriteButton clicked on row ' + e.source.row +' at ' + new Date().getSeconds());
alert('favoriteButton clicked on row ' + e.source.row);
var index = e.source.row;
var name = tableData[index];
alert('name'+name);
});
}
tableView.setData(tableData);
};
//-- Network error
loader.onerror = function(e)
{
Ti.API.info('Network error: ' + JSON.stringify(e));
};
// Send the HTTP request
loader.send();
return tableData;
};
Once you have your index, you should be able to reference your original data source by that.
var favoriteButton = Ti.UI.createButton({
title:'btn',
//font:{fontFamily:'Helvetica Neue',fontSize:15},
top:20,
left:255,
height:30,
width:50,
url:'../Images/favorite.png'
//image:'../Images/favorite.png',
name:categoryName,
address:address;//address mention here
});
row.add(favoriteButton);
favoriteButton.addEventListener('click', function(e)
{
var index = e.source.row;
var name = e.source.name;
var address = e.source.address;
alert('name'+name);
});
}
I think this might help you a lot.

titanium mobile:retrieve row title from tableview and its display in next window issue

Hello friends,
I am developing an app which displays category types using custom cell in tableview and then selects a row its go to detail which selected category type but I'm facing a problem that is I can't get row title in the next window. So please give me idea how to solve it.
Ti.include('PlacesTypeCustomCell.js');
var currentWindow = Titanium.UI.currentWindow;
var tableData = [];
// Create table
var tableData = new PlacesTypeCells();
var myTableView = Titanium.UI.createTableView
({
data:tableData,
top:45,
height:368
});
currentWindow.add(myTableView);
myTableView.addEventListener('click',function(e)
{
var index = e.index;
Ti.API.log('Row at index:'+index);
Titanium.App.Properties.setInt('index',index);
v//get each row title from tableview
var pageTitle = Titanium.App.Properties.setString('title',e.rowData.pageTitle);
Ti.API.log('Page Title:'+pageTitle);
var pageAddress = Titanium.App.Properties.setString('address',e.rowData.pageAddress);
Ti.API.log('Page Address:'+pageAddress);
var win = Titanium.UI.createWindow
({
url:'PlacesList.js',
title:'Place List'
});
Titanium.UI.currentTab.open(win,{animated:true});
});
//Custom Cell PlacesTypeCustomCell
var tableData=[];
var loader = Titanium.Network.createHTTPClient();
var url = "https://maps.googleapis.com/maps/api/place/search/json?";
url = url + "location=" + lat + ',' + lon;
url = url + "&radius=" + radius;
url = url + "&name=" + name;
url = url + "&sensor=" + sensor;
url = url + "&key=" + key;
Ti.API.info(url);
// Sets the HTTP request method, and the URL to get data from
loader.open("GET",url);
// Create our HTTP Client and name it "loader"
// Runs the function when the data is ready for us to process
loader.onload = function()
{
var obj = JSON.parse(this.responseText);
Ti.API.log(obj);
var results = obj.results;
Ti.API.log(results);
for (var i = 0; i < results.length; i++)
{
categoryName = obj.results[i].name;
reference = obj.results[i].reference;
Ti.API.log('Refernce:'+reference);
getDetailsData();
// Create a row and set its height to auto
row = Titanium.UI.createTableViewRow({height:'78'});
var placeImage = Titanium.UI.createImageView
({
image:'../iphone/appicon.png',
width:70,
height:50,
top:12,
left:5
});
// Create the label to hold the tweet message
var nameLabel = Titanium.UI.createLabel({
//text:name,
left:80,
top:5,
height:'auto',
width:200,
textAlign:'left',
font:{fontSize:12}
});
// Create the label to hold the tweet message
addressLabel = Titanium.UI.createLabel({
left:80,
top:25,
height:'auto',
width:200,
textAlign:'left',
font:{fontSize:14}
});
var arrowImage = Ti.UI.createImageView
({
image:'../iphone/appicon.png',
width:20,
height:20,
left:280,
top:30
});
nameLabel.text = categoryName;
getDetailsData(addressLabel);
row.add(placeImage);
row.add(nameLabel);
row.add(addressLabel);
row.add(arrowImage);
tableData[i] = row;
//set page title for each row
row.pageTitle = tableData[i];
row.pageAddress = tableData[i];
}
tableView.setData(tableData);
};
//PlaceList.js
var currentWindow = Titanium.UI.currentWindow;
//retrive index value
var index = Titanium.App.Properties.getInt('index');
Ti.API.log('NextView Index:'+index);
var title = Titanium.App.Properties.getString('title');
Ti.API.log('CheckInView Title:'+title);
var address = Titanium.App.Properties.getString('address');
Ti.API.log('CheckInView Address:'+address);
My problem is that I can't get row title in next window but I get index value of that row so please give me idea how to fetch it.
Just do this after the following line:
var row = Titanium.UI.createTableViewRow({height:'auto'});
Set a title as property of your row like this:
row.pageTitle = tableData[i];
And in click event you can get this property like this:
myTableView.addEventListener('click',function(e)
{
e.rowData.pageTitle
}

Resources