Thursday, July 24, 2014

titanium: include is deprecated. use require. but needs a few more lines

var module = require("pages/dictionary");
Ti.API.info(module.dictionary);

// ---- dictionary.js
var dictionary = {
A:[
{title:"ah boy", definition:"refers to a boy"},
{title:"ah gal", definition:"refers to a girl"}
],
B:[
{title:"bola", definition:"refers to a ball"},
{title:"boh", definition:"refers to nothing"}
],
//--- so on and on
};

exports.dictionary = dictionary;

Thursday, July 17, 2014

python: open a file to read, then replace string, write back to file

f = open('file.txt', 'r');
s = f.read();
print s
s = s.replace('\n', '\\n');
s = s.replace('\r', '');
# print s
f.close();
f = open('file_replaced.txt', 'w');
f.write(s);
f.close();

print "file written"

Monday, July 14, 2014

titanium - deleting data from Parse

var url = "https://api.parse.com/1/batch"; // batch function
 var client = Ti.Network.createHTTPClient({
     // function called when the response data is available
     onload : function(e) {
         Ti.API.info("Received text: \n" + this.responseText);
         textarea.value = this.responseText;
         var response = JSON.parse(this.responseText);
         Ti.API.info("Received object: \n" + response);
         //Ti.API.info("Received xml: \n" + this.responseXML);
         //alert('success');
         //popup.close();
         activityIndicator.hide();
         //process(this.responseXML);
     },
     // function called when an error occurs, including a timeout
     onerror : function(e) {
         Ti.API.debug(e.error);
         textarea.value = e.error;
         //alert('error');
         //popup.close();
         activityIndicator.hide();
       
     },
     timeout : 5000  // in milliseconds
 });
 // Prepare the connection.
 client.open("POST", url); // sending data to Parse
 //client.open("GET", url); // getting result from Parse

 // copied from Parse online settings > Application keys
 client.setRequestHeader("X-Parse-Application-Id", "/**** copied from parse.com ****/");
 // copied from Parse online settings > Application keys
  client.setRequestHeader("X-Parse-REST-API-Key", "/**** copied from parse.com ****/");
  client.setRequestHeader("Content-Type", "application/json");
 client.send(JSON.stringify({
     "requests":[
         {
           "method": "DELETE",
           "path": "/1/classes/Hello/JKWFuRnf0T"
         }
     ]
   
 }));// data to delete

returned text: [{"success":true}]

Sunday, July 13, 2014

titanium - updating data in Parse

var url = "https://api.parse.com/1/batch"; // batch function
 var client = Ti.Network.createHTTPClient({
     // function called when the response data is available
     onload : function(e) {
         Ti.API.info("Received text: \n" + this.responseText);
         textarea.value = this.responseText;
         var response = JSON.parse(this.responseText);
         Ti.API.info("Received object: \n" + response);
         //Ti.API.info("Received xml: \n" + this.responseXML);
         //alert('success');
         //popup.close();
         activityIndicator.hide();
         //process(this.responseXML);
     },
     // function called when an error occurs, including a timeout
     onerror : function(e) {
         Ti.API.debug(e.error);
         textarea.value = e.error;
         //alert('error');
         //popup.close();
         activityIndicator.hide();
       
     },
     timeout : 5000  // in milliseconds
 });
 // Prepare the connection.
 client.open("POST", url); // sending data to Parse
 //client.open("GET", url); // getting result from Parse

 // copied from Parse online settings > Application keys
 client.setRequestHeader("X-Parse-Application-Id", "/**** copied from parse.com ****/");
 // copied from Parse online settings > Application keys
  client.setRequestHeader("X-Parse-REST-API-Key", "/**** copied from parse.com ****/");
  client.setRequestHeader("Content-Type", "application/json");
 client.send(JSON.stringify({
     "requests":[
         {
             "method":"PUT",
             "path":"/1/classes/Hello/JKWFuRnf0T",
             "body":{
                 price:99.99
             }
         }
     ]
   
 }));// data to change or update


returned text:
[{"success":{"updatedAt":"2014-07-13T15:57:31.607Z"}}]

titanium - getting data from Parse. like SELECT

var url = "https://api.parse.com/1/classes/Hello"; // SELECT *

 var client = Ti.Network.createHTTPClient({
     // function called when the response data is available
     onload : function(e) {
         Ti.API.info("Received text: \n" + this.responseText);
         textarea.value = this.responseText;
         var response = JSON.parse(this.responseText);
         Ti.API.info("Received object: \n" + response);
         //Ti.API.info("Received xml: \n" + this.responseXML);
         //alert('success');
         //popup.close();
         activityIndicator.hide();
         //process(this.responseXML);
     },
     // function called when an error occurs, including a timeout
     onerror : function(e) {
         Ti.API.debug(e.error);
         textarea.value = e.error;
         //alert('error');
         //popup.close();
         activityIndicator.hide();
       
     },
     timeout : 5000  // in milliseconds
 });
 // Prepare the connection.
 //client.open("POST", url); // sending data to Parse
 client.open("GET", url); // getting result from Parse
 // copied from Parse online settings > Application keys
 client.setRequestHeader("X-Parse-Application-Id", "/** copied from parse.com **/");
 // copied from Parse online settings > Application keys
  client.setRequestHeader("X-Parse-REST-API-Key", "/** copied from parse.com **/");
   //client.setRequestHeader("Content-Type", "application/json");
 client.send();

JSON string returned.
eg.:
{"results":[
{"Description":"exciting book","price":0.99,"title":"my book","createdAt":"2014-07-08T01:48:15.369Z","updatedAt":"2014-07-08T01:48:35.968Z","objectId":"xEVblKpjTC"},
{"Description":"jack throw beans and stalk grew and he climbed and met giant","price":1.5,"title":"jack and the beanstalk","createdAt":"2014-07-13T14:55:02.571Z","updatedAt":"2014-07-13T14:55:30.630Z","objectId":"SKv9CbqKzi"},
{"title":"lord of the ring","price":15.99,"description":"frodo saves the middle-earth","createdAt":"2014-07-13T15:14:22.467Z","updatedAt":"2014-07-13T15:14:22.467Z","objectId":"JKWFuRnf0T"}]}

if need specific object, use the Id in url
eg.: https://api.parse.com/1/classes/Hello/xEVblKpjTC
response: {"Description":"exciting book","createdAt":"2014-07-08T01:48:15.369Z","objectId":"xEVblKpjTC","price":0.99,"title":"my book","updatedAt":"2014-07-08T01:48:35.968Z"}

titanium - how to send data to Parse.com thru REST API (insert)

var url = "https://api.parse.com/1/classes/Hello";

 var client = Ti.Network.createHTTPClient({
     // function called when the response data is available
     onload : function(e) {
         Ti.API.info("Received text: \n" + this.responseText);
     // returns a json string. eg.: {"createdAt":"2014-07-13T15:14:22.467Z","objectId":"JKWFuRnf0T"}
         var response = JSON.parse(this.responseText);
         Ti.API.info("Received object: \n" + response);
     
         activityIndicator.hide();
     },
     // function called when an error occurs, including a timeout
     onerror : function(e) {
         Ti.API.debug(e.error);
         textarea.value = e.error;
         activityIndicator.hide();
       
     },
     timeout : 5000  // in milliseconds
 });
 // Prepare the connection.
 client.open("POST", url);
 // copied from Parse online settings > Application keys
 client.setRequestHeader("X-Parse-Application-Id", "/**** copied from parse.com ****/");
 // copied from Parse online settings > Application keys
  client.setRequestHeader("X-Parse-REST-API-Key", "/**** copied from parse.com ****/");
   client.setRequestHeader("Content-Type", "application/json");
   // data to insert
   var data = {
           title:'lord of the ring',
           price:15.99,
           description:'frodo saves the middle-earth'
   };
 // Send the request.
 client.send(JSON.stringify(data));

titanium: activity indicator while waiting for network

var activityIndicator = Ti.UI.createActivityIndicator({
  //color: 'green',
  font: {fontSize:18},
  message: 'Loading...',

  top:10,
  left:10,
  height:20,
  width:"100%"
});

view.add(activityIndicator);
activityIndicator.show();

titanium: how to get data from internet. eg.: RSS, how to process xml

 var url = "http://www.channelnewsasia.com/rss/latest_cna_frontpage_rss.xml"; //"http://www.appcelerator.com";

 var client = Ti.Network.createHTTPClient({
     // function called when the response data is available
     onload : function(e) {
         Ti.API.info("Received text: \n" + this.responseText);
         Ti.API.info("Received xml: \n" + this.responseXML);
         //alert('success');
         process(this.responseXML);
     },
     // function called when an error occurs, including a timeout
     onerror : function(e) {
         Ti.API.debug(e.error);
         //alert('error');
     },
     timeout : 5000  // in milliseconds
 });
 // Prepare the connection.
 client.open("GET", url);
 // Send the request.
 client.send();

view.add(textarea);
self.add(view);


function process(xml){
    var items = xml.getElementsByTagName("item");
    for(var i = 0; i        Ti.API.info("items " + i + " - " + items.item(i).getElementsByTagName("title").item(0).textContent);
        Ti.API.info("content " + i + " - " + items.item(i).getElementsByTagName("description").item(0).textContent);
    }
}


Saturday, July 12, 2014

Titanium - getting GPS location and displaying on map

Ti.Geolocation.addEventListener("location", function(e){
    if(e.coords != undefined){
        http://Ti.API.info("location: " + e.coords.latitude + ", " + e.coords.longitude);
        mapview.setLocation({
            latitude:e.coords.latitude, longitude:e.coords.longitude, animate:true,
            latitudeDelta:0.005, longitudeDelta:0.005});
     }
});

Friday, July 11, 2014

map view in titanium worked, deprecated though

tested on android emulator . need to create new emulator and set API of emulator to Google API (19) and start

var win = Ti.UI.currentWindow;

var annotations=[
// convention centre: 1.311110, 103.778009
// dmit: 1.311671, 103.775800
// hilltop library: 1.311341, 103.774451
{latitude:1.311110,longitude:103.778009, title:"Convention Centre", subtitle:"Big PeRformance here?"},
{latitude:1.311671, longitude:103.775800, title:"DMIT", subtitle:"Digital Media & IT"},
{latitude:1.311341, longitude:103.774451, title:"Hilltop library ", subtitle:"to borrow books"}
];


var annotationObject=[];

Titanium.API.info(annotations.length);

for(var i=0;i{
    annotationObject[i]=Titanium.Map.createAnnotation({
        latitude:annotations[i].latitude,
        longitude:annotations[i].longitude,
        title:annotations[i].title,
        subtitle:annotations[i].subtitle,
        animate:true,
    });
}


var mapview = Titanium.Map.createView({
    top:50,
    mapType: Titanium.Map.STANDARD_TYPE,
    region: {
latitude:1.311710, longitude:103.775643,
            latitudeDelta:0.01, longitudeDelta:0.01},
    animate:true,
    regionFit:true,
    annotations:annotationObject
});
win.add(mapview);





//---- another sample
// titanium map view on SP

var mapview = Titanium.Map.createView({
    mapType: Titanium.Map.STANDARD_TYPE,
    // SP: 1.311710, 103.775643
    region: {latitude:1.311710, longitude:103.775643,
            // zoom level
            latitudeDelta:0.01, longitudeDelta:0.01},
    animate:true,
    regionFit:true,
    userLocation:false
});

win.add(mapview);

Thursday, July 10, 2014

Titanium:icons and default splash screen

icon - replace the appicon.png in android folder

then replace the respective default.png in the android folder.
eg.: Resources\android\images\res-notlong-port-hdpi for Nexus 4

delete from sqlite database in titanium

delButton.addEventListener('click', function(e){
// get data
// install db in device

var rows = db.execute('DELETE FROM hello_tbl WHERE id = ?', self.id);
Ti.API.info("data deleted: " + nameTxt.value + " , " + ageTxt.value);

self.close();

self.prevWindow.updateData();
});

updating data in sqlite database in titanium

/**
*   DBView.js
 */
var self = Ti.UI.currentWindow;
self.backgroundColor = '#333';
self.updateData = updateData;
// create view
var view = Ti.UI.createView();
var myFont = {fontSize: 18};

var cols = [20, 300];
var table = Ti.UI.createTableView();

updateData();

table.addEventListener("click", function(e){
Ti.API.info("row clicked with id: " + e.row.myIndex);
var win = Ti.UI.createWindow({
title: 'Update Data',
url:'/ui/common/UpdateData.js',
id:e.row.myIndex,
prevWindow:self
});
win.open();
});


view.add(table);
self.add(view);

function updateData(){
var tableData = [];


// get data
// install db in device
var db = Ti.Database.install('/mydata/mydb.sqlite', 'mydb');

var rows = db.execute('SELECT * FROM hello_tbl');
while (rows.isValidRow())
{

 var name = rows.fieldByName('name');
 var age = rows.fieldByName('age');
 var id = rows.fieldByName('id');
 Ti.API.info(name + ' ' + age);

 var tablerow = Ti.UI.createTableViewRow({
  className:'row',
  objName:'row',
  myIndex:id,
  height: 50
 });
 var label = Ti.UI.createLabel({text:name, font:myFont, left: cols[0]});
 var label2 = Ti.UI.createLabel({text:age, font:myFont, left: cols[1]});
 tablerow.add(label);
 tablerow.add(label2);
 tableData.push(tablerow);

 rows.next();
}
rows.close();

table.setData(tableData);
}


/**
*
*  UpdateData.js
 */

var self = Ti.UI.currentWindow;
self.backgroundColor = '#333';
// create view
var view = Ti.UI.createView();
var myFont = {fontSize: 18};
var myHeight = 50;
var myWidth = '80%';
var cols = [20, 300];
var rows = [20, 50, 120, 150, 220];

var db = Ti.Database.install('/mydata/mydb.sqlite', 'mydb');


var nameLbl = Ti.UI.createLabel({text:"Name: ", left:cols[0], top: rows[0], width:myWidth, font:myFont});
view.add(nameLbl);

var nameTxt = Ti.UI.createTextField({hintText :"Enter your name", left:cols[0], top: rows[1], width:myWidth, font:myFont});
view.add(nameTxt);

var ageLbl = Ti.UI.createLabel({text:"Age: ", left:cols[0], top: rows[2], width:myWidth, font:myFont});
view.add(ageLbl);

var ageTxt = Ti.UI.createTextField({hintText :"Enter your age", left:cols[0], top: rows[3], width:myWidth, font:myFont});
view.add(ageTxt);

var button = Ti.UI.createButton({title: 'Update Data', top: rows[4], left:cols[0], height:myHeight});
view.add(button);

button.addEventListener('click', function(e){
// get data
// install db in device


var rows = db.execute('UPDATE hello_tbl SET name = ?, age=? WHERE id = ?',
nameTxt.value, ageTxt.value, self.id);
Ti.API.info("data updated: " + nameTxt.value + " , " + ageTxt.value);

self.close();

self.prevWindow.updateData();
});

// populate data into UI
var rows = db.execute('SELECT * FROM hello_tbl WHERE id=?', self.id);
if (rows.isValidRow())
{
nameTxt.value = rows.fieldByName('name');
ageTxt.value = rows.fieldByName('age');
}

self.add(view);

adding data to sqlite db in titanium

var self = Ti.UI.currentWindow;
self.backgroundColor = '#333';
// create view
var view = Ti.UI.createView();
var myFont = {fontSize: 18};
var myHeight = 50;
var myWidth = '80%';
var cols = [20, 300];
var rows = [20, 50, 120, 150, 220];

var nameLbl = Ti.UI.createLabel({text:"Name: ", left:cols[0], top: rows[0], width:myWidth, font:myFont});
view.add(nameLbl);

var nameTxt = Ti.UI.createTextField({hintText :"Enter your name", left:cols[0], top: rows[1], width:myWidth, font:myFont})
view.add(nameTxt);

var ageLbl = Ti.UI.createLabel({text:"Age: ", left:cols[0], top: rows[2], width:myWidth, font:myFont});
view.add(ageLbl);

var ageTxt = Ti.UI.createTextField({hintText :"Enter your age", left:cols[0], top: rows[3], width:myWidth, font:myFont})
view.add(ageTxt);

var button = Ti.UI.createButton({title: 'Add Data', top: rows[4], left:cols[0], height:myHeight});
view.add(button);

button.addEventListener('click', function(e){
// get data
// install db in device
var db = Ti.Database.install('/mydata/mydb.sqlite', 'mydb');

var rows = db.execute('INSERT INTO hello_tbl (name, age) VALUES (?,?)',
nameTxt.value, ageTxt.value);
Ti.API.info("data added: " + nameTxt.value + " , " + ageTxt.value);

self.close();
})


self.add(view);

Viewing or reading data from SQLite Database in Titanium

var self = Ti.UI.currentWindow;
self.backgroundColor = '#333';
// create view
var view = Ti.UI.createView();
var myFont = {fontSize: 18};

var cols = [20, 300];
var table = Ti.UI.createTableView();
var tableData = [];


// get data
// install db in device
var db = Ti.Database.install('/mydata/mydb.sqlite', 'mydb');

var rows = db.execute('SELECT * FROM hello_tbl');
while (rows.isValidRow())
{

  var name = rows.fieldByName('name');
  var age = rows.fieldByName('age');
  Ti.API.info(name + ' ' + age);

  var tablerow = Ti.UI.createTableViewRow({
  className:'row',
  objName:'row',
  height: 50
  });
  var label = Ti.UI.createLabel({text:name, font:myFont, left: cols[0]});
  var label2 = Ti.UI.createLabel({text:age, font:myFont, left: cols[1]});
  tablerow.add(label);
  tablerow.add(label2);
  tableData.push(tablerow);

  rows.next();
}
rows.close();

table.setData(tableData);
view.add(table);
self.add(view);