Category Archives: Education

Parsing JSON data using Google GSON library in Eclipse

1. Download gson library
2. Add as external jar from your eclipse project

JSON String:
[{“ID”:”18″, “Name”:”Name A”} ,
{“ID”:”19″, “Name”:”Name B”} ,
{“ID”:”20″, “Name”:”Name C”} ,
{“ID”:”21″, “Name”:”Name D”}]

Java class to implement the parsing

public class gsonexample {

	public gsonexample(){}

	public void parseJson(String url){
			Reader reader = new InputStreamReader(new URL("url").openStream()); //Read the json output
			Gson gson = new GsonBuilder().create();
			DataObject obj = gson.fromJson(reader, DataObject.class);
		}catch(Exception e){

	private class DataObject{ //This class should match your json object structure
		private int status;
		private String error_message;
		private List<Item> item; // This is for the inner array
	    public String toString() {
	        return status + " - " + error_message+ " (" + item + ")";

	private class Item{ //This is the inner array class
		public int ID;
		public String Name;
	    public String toString() {
	        return ID + " - " + Name +"\n";

Simple Fibonacci Series

private void fibonacci(List list,int arg){
 int temp = (int)list.get(list.size()-1) + (int)list.get(list.size()-2);

Check integer pallindrome without using build-in utilities

public static boolean pallindrome(int arg){
int remainder = 0;
int newArg = arg;
int result = 0;
remainder = newArg % 10;
newArg = newArg / 10;
result = result*10 + remainder;
if(result == arg){
return true;
return false;

Exception java.util.ConcurrentModificationException on ArrayList

If you encounter exception:

Exception in thread “main” java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(
at java.util.AbstractList$

You can go around and use CopyOnWriteArrayList<E>() instead.

Detecting language change in keyboard for IOS

For detecting IOS keyboard language change when you are in textfield / textview, you can do it in
– (BOOL)textField:(UITextField *)textView shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)text

The following will detect Chinese character (in general) whenever text is input into the textfield.

// This will check if the current character user entered is not a chinese character
if([[UITextInputMode currentInputMode].primaryLanguage rangeOfString:@"zh-"].location != NSNotFound){
// Put your code here.

UIImageView aspectFit and center

Recently, I come across with a limitation where IOS SDK does not let us specified image view property to multiple flag. (e.g flagA | flagB in Android does).
There are several option out there using custom class extending the UIImageView.

For this post I will show you how to set UIImageView aspectFit and Center together (ugly workaround), this solution is not the best and has some side effect to the performance, but it is an option for people who still want it.

First, I calculate the ratio that needed to resize and set that as my new frame width/height. Then, using the new information I got, set the starting point of my frame.

If you use an UIImageView from interface.builder and set it to aspectFit, below can help you load your image programmatically and still display in center horizontal.

UIImageView *tmpView = (UIImageView *)[tmp_controller.cellPhoto viewWithTag:image_tag];
[tmpView setContentMode:UIViewContentModeScaleAspectFit];
CGSize kMaxImageViewSize = {.width = 200, .height = 200}; //set your max desire width and height here
CGSize imageSize = image.size;
CGFloat aspectRatio = imageSize.width / imageSize.height;
CGRect frame = tmpView.frame;

if (kMaxImageViewSize.width / aspectRatio <= kMaxImageViewSize.height) {
frame.size.width = kMaxImageViewSize.width;
frame.size.height = frame.size.width / aspectRatio;
} else {
frame.size.height = kMaxImageViewSize.height;
frame.size.width = frame.size.height * aspectRatio;

CGFloat startPointX = (self.view.frame.size.width/2) - (frame.size.width/2);
tmpView.frame = CGRectMake(startPointX,tmpView.frame.origin.y,frame.size.width, frame.size.height);
tmpView.image = [info objectForKey:UIImagePickerControllerOriginalImage]; //Getting image from photo album


PHP get address from coordinate using google api

This function is just a basic function to get basic address from google api, if more detail information needed, you will have to understand the json response string and customize your output from there.

In order to be able to use the google api, you will need to be registered to google developer community and has map api set to on. If you are not registered, you can find go to and start from there.

After you have setup your access to use google api, you are ready to use this function.

function for getting address using coordinates

// This function is for string null or empty check in the main function

function IsNullOrEmptyString($question){

return (!isset($question) || trim($question)==='');


function getAddress($latitude,$longitude){

$url = "$latitude,$longitude&sensor=false&token=".<google api token key here>;

$response = file_get_contents($url);

$json = json_decode($response,TRUE); //set json response to array based

$address_arr = $json['results'][0]['address_components'];

$address = "";

foreach ($address_arr as $arr1){

if(strcmp($arr1['types'][0],"street_number") == 0){

$address .= $arr1['long_name']." ";



if(strcmp($arr1['types'][0],"route") == 0){

$address .= $arr1['long_name'];



if(strcmp($arr1['types'][0],"locality") == 0){

$city = $arr1['long_name'];



if(strcmp($arr1['types'][0],"administrative_area_level_1") == 0){

$state = $arr1['long_name'];



if(strcmp($arr1['types'][0],"administrative_area_level_2") == 0){

$state2 = $arr1['long_name'];



if(strcmp($arr1['types'][0],"postal_code") == 0){

$zip_code = $arr1['long_name'];



if(strcmp($arr1['types'][0],"country") == 0){

$country = $arr1['long_name'];





$response = array("address"=>$address, "city"=>$city, "state"=>$state, "zipcode"=>$zip_code, "country"=>$country); //level_1 administrative data exist


$response = array("address"=>$address, "city"=>$city, "state"=>$state2, "zipcode"=>$zip_code, "country"=>$country); //level_1 administrative data not exist


return $response;


usage of the function. Output is an array.

$array = getAddress(37.7840,-122.4352);

To obtain address simply use:

$array->[‘address’] or
$array->[‘city’] or
$array->[‘state’] or
$array->[‘zipcode’] or

Simple php function to get coordinates from address through google services

Here I am showing you how to get coordinates from address using google api (Thanks to Google). The result will solely depends on how google support it in the future. Because google will set the 1st index result for the most relevant, thus this works quite well in general.

Function in php:

function getCoordinates($address){

$address = str_replace(" ", "+", $address); // replace all the white space with "+" sign to match with google search pattern

$url = "$address";

$response = file_get_contents($url);

$json = json_decode($response,TRUE); //generate array object from the response from the web

return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geometry']['location']['lng']);


How to call the function in php

echo getCoordinates('740 Story Rd San Jose CA 95122');

Result : 37.328865,-121.8581845

Simple Android Animation on View GONE/VISIBLE

If you just want a better transition view on GONE / VISIBLE rather than the default Android show/hide, I came across  some simple trick to make a simple animation using TranslateAnimation class.

*Note: For a better transitioning, you can use animationlistener , and setVisibility onAnimationStart() or onAnimationEnd().

// View to be animate (I use ImageView as example here)
ImageView imageView = (ImageView)findViewById(;

Below are the methods to set view from VISIBLE to GONE

// To animate view slide out from left to right
public void slideToRight(View view){
TranslateAnimation animate = new TranslateAnimation(0,view.getWidth(),0,0);
// To animate view slide out from right to left
public void slideToLeft(View view){
TranslateAnimation animate = new TranslateAnimation(0,-view.getWidth(),0,0);

// To animate view slide out from top to bottom
public void slideToBottom(View view){
TranslateAnimation animate = new TranslateAnimation(0,0,0,view.getHeight());

// To animate view slide out from bottom to top
public void slideToTop(View view){
TranslateAnimation animate = new TranslateAnimation(0,0,0,-view.getHeight());

Android Dynamic listview updates and append

I just finished my android code on generating never ending listview and just want to share what I have. It will be nice if someone out there can help me recycle my listview properly. This is not a complete solution, but should be good enough for someone to pick up the idea on how to implement it.

I will create a layout for my footer to go into

<LinearLayout xmlns:android=""
 android:text="Loading more items..."/>

Then, you will need to append the footer to your listview. In my case I put it under my onCreate();

lv = (ListView)findViewById(;
lv.addFooterView(((LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE)).inflate(R.layout.listviewfooter, null, false));

Now we need to set our listview listener so when it reach our footer view, it can grab additional items.

lv.setSelection(listviewselection); // This line is to position your list view so it does not jump to first in list after updating.
lv.setOnScrollListener(new OnScrollListener(){
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {

//get the last item that is visible on the screen
int lastItemInScreen = firstVisibleItem + visibleItemCount;

//I set a flag here to ask if the list require more items from the server
if((lastItemInScreen == totalItemCount) && flg_shouldLoad){

flg_shouldLoad = false;
listviewselection = firstVisibleItem;
Thread thread = new Thread(null, loadMoreItems);

Following, I will need a runnable to get my item from my server

//Runnable to load the items
private Runnable loadMoreItems = new Runnable() {
public void run() {

At last make sure you do a check for onclicklistener for listview to ignore the last item of your adapter, so you will not have a indexoutofbound exception.