SQL Titanium using SQLite - mysql

I have a database look like this
I'm trying to get the NamaHalaman by doing some sql Query
function getPageByMdl(modul) {
var sql = "SELECT * FROM Halaman WHERE ModulLayanan = '"+modul+"' ORDER BY Urutan ASC";
var results = [];
var sqlResultSet = db.execute(sql);
while (sqlResultSet.isValidRow()) {
results.push({
namahalaman : sqlResultSet.fieldByName('NamaHalaman')
});
sqlResultSet.next();
}
sqlResultSet.close();
return results;
}
However the result length always give me 0 although as you can see it has 2 value in it. Another problem also happen when i try to run
var sql = "SELECT Distinct ModulLayanan FROM Halaman Order ASC";
it only returned the first value from the database which is Whistleblowing system.
Oh here's my function on showing the result
function loadDetailModule() {
data = getPageByMdl(modulTemp);
if (data.length > 0) {
var tableData = [];
//get through each item
for (var i = 0; i < data.length; i++) {
var detailmodul = data[i];
//create table row
var row = Titanium.UI.createTableViewRow({
dataIndex : i,
_title : detailmodul.namahalaman,
hasChild : true,
className : 'detailmodul_halaman',
filter : detailmodul.namahalaman,
height : 70,
backgroundColor : '#fff',
});
//title label for row at index i
var titleLabel = Titanium.UI.createLabel({
text : detailmodul.namahalaman,
font : {
fontSize : 14,
fontWeight : ' bold'
},
left : 70,
top : 10,
height : 50,
width : 210,
color : '#232',
dataIndex : i
});
row.add(titleLabel);
//add our little icon to the left of the row
var iconImage = Titanium.UI.createImageView({
image : 'img/eggcooking.png',
width : 50,
height : 50,
left : 10,
top : 10
});
row.add(iconImage);
//add the row to data array
tableData.push(row);
}
// set the data to tableview's data
detailModuleTable.data = tableData;
detailModuleTable.show();
} else {
detailModuleTable.hide();
}
}
Thank you in advance

the problem is because the Titanium does not refresh your Database when you run your application.
What you need is:
1. uninstall your application in emulator
or
2. you can change the database name
Titanium.Database.install('SLTemp.sqlite', 'SLTemp1');
var db = Ti.Database.open('SLTemp1');
to
Titanium.Database.install('SLTemp.sqlite', 'SLTemp');
var db = Ti.Database.open('SLTemp');

Related

In cesium, how do you dynamically update a label over time?

I have a label that associated with a billboard/marker in cesium that I want to 'update' over time. I tried using a setTimeout to increment a variable 'count' that I assign as the label to a marker... but it doesn't increment. Is there something special I need to be doing or am missing?
You should be able to update a label just by changing its text property.
entity.label.text = 'new text';
Here's a full example:
var viewer = new Cesium.Viewer('cesiumContainer');
var image = new Image();
var entity;
image.onload = function() {
entity = viewer.entities.add({
position : Cesium.Cartesian3.fromDegrees(-75.1641667, 39.9522222),
billboard : {
position : Cesium.Cartesian3.fromDegrees(-75.1641667, 39.9522222),
scaleByDistance : new Cesium.NearFarScalar(1.5e2, 5.0, 1.5e7, 0.5),
image : image
},
label : {
text : 'Label on top of scaling billboard',
font : '20px sans-serif',
showBackground : true,
horizontalOrigin : Cesium.HorizontalOrigin.CENTER,
pixelOffset : new Cesium.Cartesian2(0.0, -image.height),
pixelOffsetScaleByDistance : new Cesium.NearFarScalar(1.5e2, 3.0, 1.5e7, 0.5)
}
});
viewer.zoomTo(viewer.entities);
};
image.src = '../images/facility.gif';
var counter = 0;
viewer.scene.postUpdate.addEventListener(function(){
if(!Cesium.defined(entity)) {
return;
}
counter += 0.04;
if(Math.cos(counter) > 0){
entity.label.text = "On";
} else {
entity.label.text = "Off";
}
});
And a live version on Sandcastle.

How to disable the Default sorting applied to groups in Kendo Grid

element.kendoGrid({
dataSource: {
data: scope.people,
group: {
field: "name"
}
},
groupable: true,
sortable: false,
pageable: {
refresh: true,
pageSizes: true
},
columns: scope.columns
});
Passed Data Source
$scope.people = [man1, man2, man3, man4];
var man1 = new Man('Test name2', 25);
var man2 = new Man('Test name1', 28);
var man3 = new Man('Test name1', 21);
var man4 = new Man('Test name3', 21);
Actual REsult :
Group are displaying in following order
First Name : Test name 1
First Name : Test name 2
First Name : Test name 3
Expected Result :
Group should display in following order
First Name : Test name 2
First Name : Test name 1
First Name : Test name 3
How do we achieve this?
By default groups are getting displayed in ascending order. But I want the order of group as it is there in the DataSource
If you can add your data through Ajax, then it's not too hard. I haven't found a way to do it without ajax though.
Your ajax would look like this:
$.ajax({
...[add your data call info here]...
}).done(function(result) {
var data = result.d.results; //this may be different for others
var sortNum = 1;
var lastVal;
for (var i = 0; i < data.length; i++) {
var val = data[i]["Firstname"];
if (!lastVal) {
lastVal = val;
}
if (val !== lastVal) {
sortNum++;
lastVal = val;
}
data[i]["SortOrder"] = sortNum;
}
});
This is if you just want to pass the data as is into your kendo grid.
Now that you have a sort column, tell kendo to group on that new column and replace the text with the original group column to display the names correctly.
//fetch FirstName value and return it to display instead of SortOrder value
function getHeader(val) {
var $data = $('.grid').data('kendoGrid').dataSource.data();
for (var i = 0; i < $data.length; i++) {
if ($data[i].SortOrder === val.value) {
return data[i].FirstName + '';
}
}
}
$('.grid').kendoGrid({
//... do all your normal kendo initialization, I'll just add the stuff you need to change
dataSource: {
schema: {
model: {
fields: { //add the new SortOrder column
SortOrder: {
type: 'number'
}
}
}
},
group: {
field: "SortOrder"
}
},
columns: [{ //add the new SortOrder column, but call the getHeader function to override the value displayed
field: "SortOrder",
hidden: true,
groupHeaderTemplate: getHeader
}]
});
That should be all you need to do. Hope this helps.

Exporting HTML table to PDF with many columns using jsPDF

I'd like to link this question that doesn't have any answers. Exporting HTML table to PDF with its format with jsPDF. I'm having the same problem with him and the tables looks exactly alike. I have a 20 column html table and I want them to be exported to pdf without any problem. I'm using jsPDF for exporting the table. I have tried the html <colgroup> tag for the column width of my table and it didn't work out. I have the first 8 columns showing and 12 columns hidden. I want all of them to be exported to pdf.
I'd like to try this code but I didn't know how I will execute it using my button in my html.
$(document).on("click", "#btnExportToPDF", function () {
var table1 =
tableToJson($('#table1').get(0)),
cellWidth = 35,
rowCount = 0,
cellContents,
leftMargin = 2,
topMargin = 12,
topMarginTable = 55,
headerRowHeight = 13,
rowHeight = 9,
l = {
orientation: 'l',
unit: 'mm',
format: 'a3',
compress: true,
fontSize: 8,
lineHeight: 1,
autoSize: false,
printHeaders: true
};
var doc = new jsPDF(l, '', '', '');
doc.setProperties({
title: 'Test PDF Document',
subject: 'This is the subject',
author: 'author',
keywords: 'generated, javascript, web 2.0, ajax',
creator: 'author'
});
doc.cellInitialize();
$.each(table1, function (i, row)
{
rowCount++;
$.each(row, function (j, cellContent) {
if (rowCount == 1) {
doc.margins = 1;
doc.setFont("helvetica");
doc.setFontType("bold");
doc.setFontSize(9);
doc.cell(leftMargin, topMargin, cellWidth, headerRowHeight, cellContent, i)
}
else if (rowCount == 2) {
doc.margins = 1;
doc.setFont("times ");
doc.setFontType("italic"); // or for normal font type use ------ doc.setFontType("normal");
doc.setFontSize(8);
doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i);
}
else {
doc.margins = 1;
doc.setFont("courier ");
doc.setFontType("bolditalic ");
doc.setFontSize(6.5);
doc.cell(leftMargin, topMargin, cellWidth, rowHeight, cellContent, i); // 1st=left margin 2nd parameter=top margin, 3rd=row cell width 4th=Row height
}
})
})
doc.save('sample Report.pdf'); })
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
// go through cells
for (var i=1; i<table.rows.length; i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data; }
This is my code btw,
function demoFromHTML() {
$(document).find('tfoot').remove();
$('#table td:nth-child(8)').remove();
var pdf = new jsPDF('p', 'pt', 'letter', true);
// source can be HTML-formatted string, or a reference
// to an actual DOM element from which the text will be scraped.
source = $('#table')[0];
// we support special element handlers. Register them with jQuery-style
// ID selector for either ID or node name. ("#iAmID", "div", "span" etc.)
// There is no support for any other type of selectors
// (class, of compound) at this time.
specialElementHandlers = {
// element with id of "bypass" - jQuery style selector
'#bypassme': function (element, renderer) {
// true = "handled elsewhere, bypass text extraction"
return true
}
};
margins = {
top: 80,
bottom: 60,
left: 55,
width: 522
};
// all coords and widths are in jsPDF instance's declared units
// 'inches' in this case
pdf.fromHTML(
source, // HTML string or DOM elem ref.
margins.left, // x coord
margins.top, { // y coord
'width': margins.width, // max width of content on PDF
'elementHandlers': specialElementHandlers
},
function (dispose) {
// dispose: object with X, Y of the last line add to the PDF
// this allow the insertion of new lines after html
var name = document.getElementById("name").innerHTML;
pdf.save(name);
}, margins);
setTimeout("window.location.reload()",0.0000001);
}
With this code btw, $(document).find('tfoot').remove(); $('#table td:nth-child(8)').remove(); I remove my footer and the 8th column of my table.

Titanium appcelerator : Lazy loading concept in table view while loading data using JSON

I have used Google Places API in order to display various places. I want at a time to display 20 places and when user scrolls the table view and reaches last field I want to add the rest of data and so on. I have created a function which returns the view and works perfectly excluding one thing. When further data is not available then it goes on loading the last data which is already loaded. Here goes my code.
Ti.include('Functions/get_lat_long.js');
var myTable = Ti.UI.createTableView();
var next_page;
var nxt_pge_tkn;
var tableData = [];
function json_parsing(url,firsttime,winloading)
{
var view1=Ti.UI.createView({
//height : '100%',
width : '100%',
backgroundColor : '#EDDA74',
top : '10%',
borderColor : "black"
});
//For storing url in case next_page_token variable is invalid
var curloc=Ti.App.Properties.getString("curlocation");
//calling method in order to retrive latitude and longitude of current location
get_latitude_longitude(curloc);
//setting the base url that have been initialized in global.js file
var baseurl=Ti.App.Properties.getString("preurl");
//storing lat and lng file that have been initialized in get_lat_lon.js file get_latitude_longitude function
var lat=Ti.App.Properties.getString("curlat");
var lng=Ti.App.Properties.getString("curlng");
//Storing radius which have been initialized in global.js file
var radiusmts=Ti.App.Properties.getInt("curradius")*1000;
//setting location type from the value that have been selected in app.js file by user
var loc_type=Ti.App.Properties.getString("curcategory");
//fetching and storing key which have been initialized in global.js file
var key=Ti.App.Properties.getString("apikey");
if(firsttime==true)
{
winloading.open();
var completeurl=baseurl+lat+","+lng+"&radius=" + radiusmts+ "&types=" + loc_type+ "&sensor=false&key=" + key;
}
else
{
winloading.show();
var completeurl=url;
}
var client = Ti.Network.createHTTPClient();
Ti.API.info("complete url " +completeurl);
client.open('GET',completeurl);
client.onload = function(e) {
//For getting next_page_token so that next page results could be displayed
var json = JSON.parse(this.responseText);
if(json.next_page_token)
{
Ti.API.info("Next page token found ");
next_page=true;
nxt_pge_tkn=json.next_page_token;
}
else
{
Ti.API.info("Next page token not found ");
next_page=false;
}
if(json.results.length==0)
{
var lblno_record=Titanium.UI.createLabel({
text : "No Record Found",
color : "black",
font : {fontSize : "25%" }
});
view1.add(lblno_record);
}
else
{
for(var i=0; i <json.results.length;i++)
{
//Ti.API.info("Place " + json.results[i].name+ " Lat " + json.results[i].geometry.location.lat + " Lng " + json.results[i].geometry.location.lng);
var row = Ti.UI.createTableViewRow({
className : "row"
//height : "80%"
});
//For temporary storing name in name variable
var name=json.results[i].name;
//Logic for shortening string in order to avoid overlapping of string
(name.length>35)?name=name.substr(0,34)+ "..." :name=name;
//Create label for displaying the name of place
var lblname=Ti.UI.createLabel({
//text : json.results[i].name,
text : name,
color : "black",
font : {fontSize : "20%"},
left : "22%",
top : "5%"
});
Ti.API.info("Name :- " + name);
row.add(lblname);
var add= json.results[i].vicinity;
(add.length>125) ? add=add.substr(0,123)+ ". ." : add=add;
var lbladdress=Ti.UI.createLabel({
text : add,
color : "black",
font : {fontSize : "15%"},
left : "22%",
top : "30%",
width : "71%"
});
row.add(lbladdress);
var imgico=Ti.UI.createImageView({
image : json.results[i].icon,
height : "90",
width : "90",
left : "1%",
top : "3%"
//bottom : "10%"
});
row.add(imgico);
tableData.push(row);
}
//setting data that have been set to mytable view
myTable.setData(tableData);
view1.add(myTable);
}
winloading.hide();
};
client.onerror=function(e){
alert("Network Not Avaliable");
};
myTable.addEventListener('scroll',function(e){
var first=e.firstVisibleItem;
var visible=e.visibleItemCount;
var total=e.totalItemCount;
Ti.API.info("Value of next_page_token before loop " + next_page);
if(next_page==true && first+visible==total )
{
Ti.API.info("Value of next_page_token in loop " + next_page);
var newurl="https://maps.googleapis.com/maps/api/place/nearbysearch/json?pagetoken="+nxt_pge_tkn+"&sensor=false&key="+key;
firsttime=false;
winloading.show();
//myTable.removeEventListener('scroll',function(e){});
json_parsing(newurl,firsttime,winloading);
//get_next_page(newurl);
}
});
client.send();
return view1;
client.clearCookies();
}
I was looking through your code and I would like to point:
There is an important issue with the block:
myTable.addEventListener('scroll',function(e){
...
});
this block is called each time you call your json_parsing function. Because of that you will have several functions attached to myTable scroll event. I'm sure that this isn't your intention. You should put it out of json_parsing.
About your specific issue you could try to look at the json.next_page_token value in your client.onload function:
client.onload = function(e) {
//For getting next_page_token so that next page results could be displayed
var json = JSON.parse(this.responseText);
Ti.API.info(JSON.stringify(this.responseText);
if(json.next_page_token)
{
...
maybe the value is an empty object {} or a 'false' string that will return a thruthy value. Don't forget that in javascript there are only 6 falsy values: false, undefined, null, 0, '' and NaN.
In practice this is a minor issue, but in documentation HTTPClient.onload and HTTPClient.onerror functions must be set before calling HTTPClient.open function
BTW, you have unreachable code at the end of your json_parsing function, but I think you already know that :-)
client.send();
return view1;
client.clearCookies(); //Unreachable code

how do I changes a graph's theme based on a value?

Using WebMatrix and razor (cshtml)
I have a chart, but the bars are default blue. I want to change their colour, based on their value ie a trigger value or target value.
How do I do this? I have a graph which uses the following code:
var db = Database.Open("data");
var itot = db.QueryValue("SELECT COALESCE(SUM(SUBTOTAL),0) from dbo.DR_TRANS where TRANSDATE = datediff(d,0,getdate()) and transtype = 1 and SUBTOTAL >0") ?? 0;
var ctot = db.QueryValue("SELECT COALESCE(SUM(SUBTOTAL),0) from dbo.DR_TRANS where TRANSDATE = datediff(d,0,getdate()) and TRANSTYPE = 1 and SUBTOTAL <0") ?? 0;
var itotnn = itot ?? 0;
var ctotnn = ctot ?? 0;
var nett = itotnn + ctotnn ?? 0;
var myChart = new Chart(width: 160, height: 500)
.AddTitle("Sales")
.AddSeries(
name: "Today",
xValue: new[] { "Actual", "Target" },
yValues: new[] { nett, 18200 })
.Write();`