Author Archives: colinyeoh

Android MapFragment exception when clicked twice

My application crashed when I re-open the same MapFragment again twice.

E/AndroidRuntime(27409): Caused by: java.lang.IllegalArgumentException: Binary XML file line #5: Duplicate id 0x7f070039, tag null, or parent id 0xffffffff with another fragment for com.google.android.gms.maps.MapFragment

I solved it by declaring the view in my fragment where I called the map to static. By this way, I only create a new view if it is null, thus avoiding it to recreate the view again.

MapFragment.java

    static View rootView;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    	if(rootView==null){
    		rootView = inflater.inflate(R.layout.MapFragment, container, false);
    	}
        return rootView;
    }

MapFragment.xml

	<fragment 
	    android:id="@+id/mapview"
	    android:layout_width="match_parent"
	    android:layout_height="match_parent"
        class="com.google.android.gms.maps.MapFragment"/>
Advertisements

Getting Date information from MongoDB’s document objectid

This post is for mongodb java api only.


	private Date getTimeStampFromID() {
        DB db = connectDB();
        DBCollection collection = db.getCollectionFromString("database");
		DBCursor cursor = collection.find();
		while(cursor.hasNext()){
			return (new Date(((ObjectId)cursor.next().get(TAG_ID)).getTime()));
		}
	}

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";
	    }
	}
}

Create simple JSON data from PHP from mysql query

function was not tested, minor modification will be needed. For this in Java

Example output:
{
“status”:”200″,
“error_message”:””,
“item”:[
{“ID”:”18″, “Name”:”Item A”} ,
{“ID”:”19″, “Name”:”Item B”} ,
{“ID”:”20″, “Name”:”Item C”} ,
{“ID”:”21″, “Name”:”Item D”}
]
}

</pre>
function constructJson($query){
 $json_str = "";
 $row_count = 0;
 if($total=mysql_num_rows($query)){
 $json_str = constructJsonHead().constructJsonStatus(200,"")."[";
 $json_item = "";
 while($data=mysql_fetch_assoc($query)){
 $count = 0;
 if(count($data)>1)
 $json_item .= constructJsonHead();

foreach($data as $key => $value){
 if(count($data)>1)
 $json_item .= "\"$key\":\"$value\"";
 else
 $json_item .= "\"$value\"";

$count++;
 if($count < count($data)) $json_item .= ",\n"; } $row_count++; if(count($data) > 1)
 $json_item .= constructJsonTail()."\n";

if($row_count < $total)
 $json_item .= ",\n";

}
 }else{
 $json_str .= constructJsonHead().constructJsonStatus(201,"No Item")."[]".constructJsonTail();
 }
 return $json_str.$json_item."]".constructJsonTail();
}

function constructJsonStatus($response_code,$msg){
 return "\"status\":\"$response_code\",\"error_message\":\"$msg\",\"item\":";
}

function constructJsonHead(){ return "{";}
function constructJsonTail(){ return "}";}
<pre>

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>

Convert integer array to integer

This is a simple function on how one can convert an integer array (int[]) to integer value

</pre>
public int add(int[] array) {
int len = array.length;
int tmp = 0;
for(int i: array){
tmp += i*((int)Math.pow(10,--len));
}

return tmp;
}
<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