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

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
}

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).

How to trigger the change event of Kendo Jquery Spreadsheet when using custom Paste function?

I tried the below custom paste function to paste only values but it doesn't trigger the change event in order for me to sync the data to the data source.
Dojo Demo Link
...
change: onExcelChange,
paste: function(e) {
e.preventDefault()
var currentRange = e.range;
var fullData = e.clipboardContent.data;
var mergedCells = e.clipboardContent.mergedCells;
var topLeft = currentRange.topLeft();
var initialRow = topLeft.row;
var initialCol = topLeft.col;
var origRef = e.clipboardContent.origRef;
var numberOfRows = origRef.bottomRight.row - origRef.topLeft.row + 1;
var numberOfCols = origRef.bottomRight.col - origRef.topLeft.col + 1;
var spread = e.sender;
var sheet = spread.activeSheet();
var rangeToPaste = sheet.range(initialRow, initialCol, numberOfRows, numberOfCols);
sheet.batch(function() {
for(var i = 0; i < fullData.length; i += 1) {
var currentFullData = fullData[i];
for(var j = 0; j < currentFullData.length; j += 1 ) {
var range = sheet.range(initialRow + i, initialCol + j);
var value = currentFullData[j].value;
if (value !== null) {
range.input(value);
range.format(null);
}
}
}
sheet.select(rangeToPaste);
}, { layout: true, recalc: true });
} ...
I have tried to use recalc: true in sheet.batch to trigger the change to no avail. Any help would be greatly appreciated.
All Kendo widgets inherit from Observable, which has a trigger method:
var obj = new kendo.Observable();
obj.bind("myevent", function(e) {
console.log(e.data); // outputs "data"
});
obj.trigger("myevent", { data: "data" });
You need to manually trigger the Spreadheet's change event with its correct parameters.

Ckeditor scrollbar marker / Text Position Indicator

I would like to implement scrollbar marker into ckeditor and i can't seem to find the right way to do it i have triyed this code
var win = new CKEDITOR.dom.window( window );
var pos = win.getScrollPosition();
console.log(pos);
but it only return the google chrome scrollbar x=0 & Y=0
var win = new CKEDITOR.dom.window( domWindow );
var pos = win.getScrollPosition();
console.log(pos);
and this give me an error domWindow is not defined
i found this example it may help: https://codepen.io/Rplus/pen/mEjWJm
(() => {
var containerQS = '.article';
var container = document.querySelector(containerQS);
var form = document.querySelector('.form');
var input = form.querySelector('input[type="text"]');
var markClass = 'mark';
var markerHeight = '2px';
var _color = 'currentColor';
var containerY = container.offsetTop;
var containerH = container.scrollHeight;
var customStyle = document.createElement('style');
container.appendChild(customStyle);
var renderScrollMarker = ($parent, posArr) => {
var _posArr = posArr.map(i => {
return `transparent ${i}, ${_color} ${i}, ${_color} calc(${i} +
${markerHeight}), transparent calc(${i} + ${markerHeight})`;
});
customStyle.innerHTML = `article::-webkit-scrollbar-track {
background-image: linear-gradient(${_posArr.join()});
}`;
};
var calcEleRelativePos = ($ele) => {
return ($ele.offsetTop - containerY) / containerH;
};
var markOpt = {
className: markClass,
done: function () {
var marks = document.querySelectorAll(`.${markClass}`);
var allY = [].map.call(marks, (mark) => {
return (calcEleRelativePos(mark) * 100).toFixed(2) + '%';
});
renderScrollMarker(container, allY);
console.log(allY);
}
};
var instance = new Mark(container);
form.addEventListener('submit', (e) => {
e.preventDefault();
var _text = input.value.trim();
console.log(_text, form.oldText);
if (_text === '') {
instance.unmark(markOpt);
return;
}
form.oldText = _text;
instance.unmark().mark(_text, markOpt);
});
// trigger
form.querySelector('input[type="submit"]').click();
})();
but as ckeditor secures a lot of element, i would love to know if any one has done this before with CKeditor
i just got the real editor scrollbar position, i only need to put a marker using style or any availble methode
var win=CKEDITOR.instances.editor1.document.getWindow();
var pos = win.getScrollPosition().y;
console.log(pos);
this worked for me :
var jqDocument = $(editor.document.$);
var documentHeight = jqDocument.height();
var scrollTo =jqDocument.scrollTop();
var docHeight = jqDocument.height();
var scrollPercent = (scroll)/(docHeight);
var scrollPercentRounded = Math.round(scrollPercent*100);
$(".ui-slider-handle").css("bottom", 100-scrollPercentRounded+"%");

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:onload function called issue in json parsing

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;

Resources