Category Archives: Education

Parsing JSON data using Google GSON library in Eclipse

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

JSON String:
{
“status”:”200″,
“error_message”:”Success”,
“item”:
[{“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){
		try{
			Reader reader = new InputStreamReader(new URL("url").openStream()); //Read the json output
			Gson gson = new GsonBuilder().create();
			DataObject obj = gson.fromJson(reader, DataObject.class);
			System.out.println(obj);
		}catch(Exception e){
			System.out.println(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
		@Override
	    public String toString() {
	        return status + " - " + error_message+ " (" + item + ")";
	    }
	}

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

Simple Fibonacci Series


private void fibonacci(List list,int arg){
 if(arg==0){
 list.add(0);
 }else{
 if(list.isEmpty()){
 list.add(0);
 list.add(1);
 }
 int temp = (int)list.get(list.size()-1) + (int)list.get(list.size()-2);
 if(arg>=temp){
 list.add(temp);
 fibonacci(list,arg);
 }
 }
 }

Check integer pallindrome without using build-in utilities

</pre>
public static boolean pallindrome(int arg){
int remainder = 0;
int newArg = arg;
int result = 0;
while(newArg!=0){
remainder = newArg % 10;
newArg = newArg / 10;
result = result*10 + remainder;
}
if(result == arg){
return true;
}else{
return false;
}
}
<pre>

Exception java.util.ConcurrentModificationException on ArrayList

If you encounter exception:

Exception in thread “main” java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343)

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 https://code.google.com/apis/ 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 = "http://maps.googleapis.com/maps/api/geocode/json?latlng=$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']." ";

continue;

}

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

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

continue;

}

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

$city = $arr1['long_name'];

continue;

}

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

$state = $arr1['long_name'];

continue;

}

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

$state2 = $arr1['long_name'];

continue;

}

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

$zip_code = $arr1['long_name'];

continue;

}

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

$country = $arr1['long_name'];

continue;

}

}

if(!IsNullOrEmptyString($state)){

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

}else{

$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
$array->[‘country’]

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 = "http://maps.google.com/maps/api/geocode/json?sensor=false&address=$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(R.id.imageview);

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);
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
view.setVisibility(View.GONE);
}
// To animate view slide out from right to left
public void slideToLeft(View view){
TranslateAnimation animate = new TranslateAnimation(0,-view.getWidth(),0,0);
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
view.setVisibility(View.GONE);
}

// To animate view slide out from top to bottom
public void slideToBottom(View view){
TranslateAnimation animate = new TranslateAnimation(0,0,0,view.getHeight());
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
view.setVisibility(View.GONE);
}

// To animate view slide out from bottom to top
public void slideToTop(View view){
TranslateAnimation animate = new TranslateAnimation(0,0,0,-view.getHeight());
animate.setDuration(500);
animate.setFillAfter(true);
view.startAnimation(animate);
view.setVisibility(View.GONE);
}

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="http://schemas.android.com/apk/res/android"
 android:orientation="horizontal"
 android:layout_width="fill_parent"
 android:gravity="center_horizontal"
 android:padding="3dp"
 android:layout_height="fill_parent">
 <TextView
 android:id="@+id/listfooter"
 android:layout_width="wrap_content"
 android:layout_height="fill_parent"
 android:gravity="center"
 android:padding="8dp"
 android:textStyle="bold"
 android:text="Loading more items..."/>
</LinearLayout>

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

lv = (ListView)findViewById(R.id.getdish_list);
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(){
@Override
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);
thread.start();
}
}
});

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


//Runnable to load the items
private Runnable loadMoreItems = new Runnable() {
@Override
public void run() {
getMoreItem();
}};

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.