Monday, August 08, 2016

Android: BLOB (PHP) to Android (Java)

Image stored as BLOB in mysql.

To load image in android:
  1. Encode image binary data with base64. $obj->picture = base64_encode($binaryData);
  2. Encode in json. json_encode($obj)
  3. Receive data in android
  4. Get byte[] using Base64.decode.
  5. Get bitmap .Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length); 

          byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);

Monday, August 01, 2016

Android: Adding header info when fetching or sending data to server-side script

With reference to previous video on fetching and posting data from/to the web.
Example: 
conn.setDoOutput(true); // POST
// prepare headers
conn.setRequestProperty("X-Parse-Application-Id", /*** your parse app id in parse.com ***/);
conn.setRequestProperty("X-Parse-REST-API-Key", /*** your parse REST API key in parse.com ***/);
conn.setRequestProperty("Content-Type", "application/json");

Android: Adding header info when fetching or sending data to server-side script

With reference to previous video on fetching and posting data from/to the web.
Example: 
conn.setDoOutput(true); // POST
// prepare headers
conn.setRequestProperty("X-Parse-Application-Id", /*** your parse app id in parse.com ***/);
conn.setRequestProperty("X-Parse-REST-API-Key", /*** your parse REST API key in parse.com ***/);
conn.setRequestProperty("Content-Type", "application/json");

Android: Adding header info when fetching or sending data to server-side script

With reference to previous video on fetching and posting data from/to the web.
Example: 
conn.setDoOutput(true); // POST
// prepare headers
conn.setRequestProperty("X-Parse-Application-Id", /*** your parse app id in parse.com ***/);
conn.setRequestProperty("X-Parse-REST-API-Key", /*** your parse REST API key in parse.com ***/);
conn.setRequestProperty("Content-Type", "application/json");

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

Android: SQLite database and ListView

Reading data from SQLite database and using it in ListView

Android: SQLite Databases

Create a SQLite database


Insert data into database table


Delete data in database table


Update data in database table


Reading data from database table and using a loop to process the data retrieved



Android: posting data to server side script

Posting data to PHP script


Using StringBuilder to format the data string to prepare to send to server side

Android: parsing XML and JSON

Parsing XML content


sample XML data:
<channel>
<title>Singapore - Nowcast and Forecast</title>
<description>3 hour Forecast</description>
<item>
<title>Nowcast Table</title>
<category>Singapore Weather Conditions</category>
<weatherForecast>
<area name="ANG MO KIO" forecast="Partly cloudy " icon="PC" zone="C" lat="1.37000000" lon="103.84940000"/>
<area name="BEDOK" forecast="Partly cloudy " icon="PC" zone="E" lat="1.32403830" lon="103.92003560"/>
<area name="BISHAN" forecast="Partly cloudy " icon="PC" zone="C" lat="1.35120000" lon="103.84850000"/>
<area name="BUKIT BATOK" forecast="Partly cloudy " icon="PC" zone="W" lat="1.34910000" lon="103.74970000"/>
<area name="BUKIT PANJANG" forecast="Showers " icon="SH" zone="C" lat="1.38080000" lon="103.76250000"/>
</weatherForecast>
</item>

</channel>

Parsing JSON


Sample JSON data: 
{"coord":{"lon":103.85,"lat":1.29},"weather":[{"id":803, "main":"Clouds", "description":"broken clouds", "icon":"04d"}],"base":"cmc stations","main":{"temp":31.97, "pressure":1010, "humidity":63, "temp_min":31, "temp_max":33},"wind":{"speed":5.7,"deg":80},"clouds":{"all":75}, "dt":1451979432, "sys": {"type":1, "id":8143, "message":0.0033, "country":"SG", "sunrise":1451948892, "sunset":1451992281},"id":1880252,"name":"Singapore","cod":200}

Android: getting and reading online content


Setting up: XML, manifest


Fetching the content from URL using a background task


Reading the fetched content using Stream readers.

Android: Threading, Asynchronous Tasks

Create an AsyncTask to perform a task running in the background

Android videos: Activity, Button, onClick

How to create a new Activity in android studio

Create a button and make it do something when clicked

How to go to a new Activity when a button is clicked

jQuery videos: HTML forms, jQuery and PHP

Form submission


Reading JSON from PHP 

Reading HTML from PHP


Send data to PHP

Wednesday, March 18, 2015

python with win32 api

ref: http://sourceforge.net/projects/pywin32/

import win32com.client
import win32api
import win32con
import time

def IsPressed(key):
    # ref: https://msdn.microsoft.com/en-us/library/windows/desktop/ms646301%28v=vs.85%29.aspx
    return win32api.GetKeyState(key) & 0x8000 == 0x8000

exit = False;
# for tracking key state
prevSpace = 0;
prevUp = 0;
currentSpace = 0;
currentUp = 0;

# loop to track key state
while (exit == False):
    currentSpace = IsPressed(win32con.VK_SPACE);
    currentUp = IsPressed(win32con.VK_UP);
    if IsPressed(win32con.VK_ESCAPE):
       exit = True;
       print "Escape"
    prevSpace = currentSpace;
    prevUp = currentUp;
    time.sleep(0.0001)


# if need to send key to another app
shell = win32com.client.Dispatch("WScript.Shell")
shell.AppActivate("app to activate or send key to ...")
shell.SendKeys("whatever key to send", 0)

python with de facto GUI library. standard library Tk


from Tkinter import *

def bClick():
    t.set(t2.get())

root = Tk()
t = StringVar()
t2 = StringVar()

# create UI elements
label = Label(root, textvariable=t)
entry = Entry(root, textvariable=t2)
b = Button(root, text="Click Me!", command = bClick)

# layout UI elements
label.pack()
entry.pack()
b.pack()

t.set("Hello Label");

root.mainloop()

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;

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}]