Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Monday, August 01, 2016

Android: WebView

WebView demo to display HTML page in Activity and to enable Javascript


Adding Javascript interface to WebView to allow Javascript to communicate with and use Java classes

jQuery videos: HTML forms, jQuery and PHP

Form submission


Reading JSON from PHP 

Reading HTML from PHP


Send data to PHP

Thursday, February 05, 2015

Angular JS: how to share variables among different controllers or scope

Using services to create application data to be shared among different controllers or different scopes.
something like a global javascript variable in a single page app. not really session variable as the variable will reset after the page is refreshed.

HTML:

<html data-ng-app="demoApp" >
    <head>
        <title>Angular Demo</title>
    </head>
    <body data-ng-controller="MyController">
        <h1>Hello Angular</h1>
     
        <ul>
            <li><a ng-click="myMethod('clicked')" href="#/SecondPage">second page</a></li>
            <li><a href="#/ThirdPage">third page</a></li>
        </ul>
        <div ng-view></div>
        <script src="angular.min.js"></script>
        <script src="angular-route.min.js"></script>
        <script src="test01.js"></script>
    </body>
</html>


JS:

 var demoApp = angular.module('demoApp', ['ngRoute']);
// add service as dependencies
demoApp.controller('MyController', ['$scope', 'myService', '$route',
                        // add service as parameter
                        function($scope, myService, $route){
    console.log("MyController");
                         
    $scope.mydata = myService; // add service object to scope
 

    $scope.myMethod = function(special){
        console.log("myMethod called: " + special);
        myService.age++;
        myService.phone.price += 0.1;
        myService.addFriend("Friend " + myService.age);
        console.log(myService);
    };
}]);

//Define Routing for app
demoApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/SecondPage', {
        templateUrl: 'second.html',
        controller: 'MyController' // can be different
    }).
      when('/ThirdPage', {
        templateUrl: 'third.html',
        controller: 'MyController' // can be different
      }).
      otherwise({
        redirectTo: '/SecondPage'
      });
}]);

// service
demoApp.factory('myService', function() {
    console.log("service starting");
    // object of this service
  var mydata = {
      // add properties
      name: "My Data",
      age: 30,
      friends: ["Tarth Bader", "Koda", "Kan zolo"],
      phone: {brand: "orange", model: "oPhone Plus", price:2000},
  };
    // add methods
    mydata.addFriend = function(friend){
        this.friends.push(friend);  
    };
  // return service
  return mydata;
});


second.html:
<div>{{ mydata.name }} is of {{mydata.age}}</div>
<ul>
    <li ng-repeat="friend in mydata.friends">{{friend}}</li>
</ul>

Angular JS: how to use separate html to layout the web app

different html to show different UI of the web app. 

HTML: 

<html data-ng-app="demoApp" >
    <head>
        <title>Angular Demo</title>
    </head>
    <body data-ng-controller="MyController">
        <h1>Hello Angular</h1>
        <input type="text" ng-model="name"/> {{name}}
        <div>
            {{age}}
        </div>
        <ul>
            <li><a ng-click="myMethod('clicked')" href="#/SecondPage">second page</a></li>
            <li><a href="#/ThirdPage">third page</a></li>
        </ul>
        <div ng-view><!-- the content from other html file will display here --></div>
        <script src="angular.min.js"></script>
        <script src="angular-route.min.js"></script>
        <script src="test01.js"></script>
    </body>
</html>


JS:

var demoApp = angular.module('demoApp', ['ngRoute']);
demoApp.controller('MyController', function($scope){
    console.log("MyController");
    $scope.hello = "Hello from AngJS";
    $scope.customers = ["dave", "larry"];
    $scope.age = 20;
    
    $scope.message = 'This is a new screen';
    
    $scope.myMethod = function(special){
        console.log("myMethod called: " + special);
        $scope.message = special;
    };
});

//Define Routing for app
demoApp.config(['$routeProvider',
  function($routeProvider) {
    $routeProvider.
      when('/SecondPage', {
        templateUrl: 'second.html',
        controller: 'MyController' // can be different controller. will instantiate new controller. different scope
    }).
      when('/ThirdPage', {
        templateUrl: 'third.html',
        controller: 'MyController
// can be different controller. will instantiate new controller. different scope
      }).
      otherwise({
        redirectTo: '/SecondPage'
      });
}]);

second.html:

<div>{{message}} </div> <!-- can add other HTML tag -->

third.html:

<div>{{hello}} </div> <!-- can add other HTML tag -->

Angular JS: starting out

basic hello world

HTML: 

<html data-ng-app="demoApp" >
    <head>
        <title>Angular Demo</title>
    </head>
    <body data-ng-controller="MyController">
        <h1>Hello Angular</h1>
        <input type="text" ng-model="name"/> {{name}}
        <div>
            {{age}}
        </div>
        
        <script src="angular.min.js"></script>
        <script src="test01.js"></script>
    </body>
</html>

JS:

var demoApp = angular.module('demoApp', [ ]);
demoApp.controller('MyController', function($scope){
    console.log("MyController");
    $scope.hello = "Hello from AngJS";
    $scope.customers = ["dave", "larry"];
    $scope.age = 20;
    
    $scope.myMethod = function(special){
        console.log("myMethod called: " + special);
        $scope.message = special;
    };
});

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;

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

Thursday, May 29, 2014

titanium: Option dialog

//-- Option Dialog
var optdialog = Ti.UI.createOptionDialog({
 cancel: 2,
 options: ['2 hours', '4 hours', '8 hours'],
 buttonNames: ["Cancel"],
 selectedIndex: 2,
 destructive: 0,
 title: 'Sleep'
});
optdialog.show();

optdialog.addEventListener('click', function(e){
Ti.API.info("option dialog ended with: "  + e.index);
});