""

Archive for July, 2011

Today i was doing some experiment with google translate API. I was trying to use google translate API with AS3. I found many snippets while googling that was using flex but i wanted to do it in flash as3. So I wrote a very basic code snippet to translate text from one language to other using google translate API.

Well i have created two combobox on my fla. I have given instance name to them and then i am just taking the language input for translating text from one language to other.

The main crucial part:

‘http://ajax.googleapis.com/ajax/services/language/translate’+’?v=2.0’+’&q=’+escape(my_input)+’&langpair=’+’es’+’%7C’+’en’

I am just making a GET HTTP Call to google translate API passing input, and language pair (i.e en(english) to es(espanol) etc). It returns result in JSON. On my flash client i decode that JSON and display the translated result.
Note: escape method is used to encode the string to url encoded format

Here is the source code:

package 
{
	import com.adobe.serialization.json.JSON;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.net.URLRequestMethod;
	import flash.net.URLVariables;
	import fl.data.DataProvider; 
	
	/**
	 * ...
	 * @author padam
	 */
	public class Main extends Sprite 
	{
		
		public function Main():void 
		{
			if (stage) init();
			else addEventListener(Event.ADDED_TO_STAGE, init);
		}
		
		private function init(e:Event = null):void 
		{
			removeEventListener(Event.ADDED_TO_STAGE, init);
			// entry point
			
			initGUI();
			button_p.addEventListener(MouseEvent.CLICK, translate);
		}
		
		private function initGUI():void {
			var itemsFrom:Array = [ 
			{label:"English", data:"en"}, 
			{label:"Spanish", data:"es"}, 
			{label:"French", data:"fr"}, 
			{label:"Italian", data:"it"}
			];
			
			var itemsTo:Array = [
			{label:"Hindi", data:"hi"},
			{label:"English", data:"en"}, 
			{label:"Spanish", data:"es"}, 
			{label:"French", data:"fr"}, 
			{label:"Italian", data:"it" }
			];
			
			fromLanguageCombo.prompt = "Select Language"; 
			fromLanguageCombo.dataProvider = new DataProvider(itemsFrom);
			toLanguageCombo.dataProvider = new DataProvider(itemsTo);
			
		}
		
		private function translate(event:MouseEvent):void {
			var request:URLRequest=new URLRequest();
			request.url='http://ajax.googleapis.com/ajax/services/language/translate'+'?v=2.0'+'&q='+escape(fromInput.text)+'&langpair='+fromLanguageCombo.selectedItem.data+'%7C'+toLanguageCombo.selectedItem.data;
			request.method = URLRequestMethod.GET;
			
			var loader:URLLoader=new URLLoader();
			loader.addEventListener(Event.COMPLETE,messageSent);
			try 
			{
				loader.load(request);
			} 
			catch (error:Error) 
			{
				
			}
		}
		
		private function messageSent(evt:Event):void
		{
			var loader:URLLoader=URLLoader(evt.target);
			var result:String = loader.data as String;
			
			var json_1:Object = JSON.decode(result);
			output.text = json_1["responseData"]["translatedText"];
			translationLabel.text = fromLanguageCombo.selectedItem.label + " to " + toLanguageCombo.selectedItem.label+" translation";
		
		}
		
	}
	
}

Well there is nothing much in code. Just taking the language values from two combo box list and passing it to the translate api. Then after decoding json that i received from api call, i am displaying on textfield. Anyway please note that translate api has been officialy depracated.

Here is the quote from API site:

Important: The Google Translate API has been officially deprecated as of May 26, 2011. Due to the substantial economic burden caused by extensive abuse, the number of requests you may make per day will be limited and the API will be shut off completely on December 1, 2011. For website translations, we encourage you to use the Google Translate Element.

Gracias.

While working on submitting and retrieving global game high scores from a remote database like mysql i learned few things. During start experiment i decided to use PHP to connect to mysql database. What i was trying to do is that i wanted to call php, then php would make a database connection and make a sql query and retrieve the result, then php would encode that result into JSON format and i would decode this JSON at my android program and display the results. I haven’t done much PHP before(never actually setup PHP server before :D). So i came to know this xampp server, so i installed/setup the xampp server(its a php apache server and it comes with mysql also). I am not telling how to setup xampp and create a databse and tables as you can find it in their wiki.

I create a php file, which makes a database connection and makes a query and encodes a result. As i told before i am not familiar to PHP so i wrote this code looking here and there by googling it :D. Code looks like this:


Well code is not that hard to understand. You are making a mysql connection by providing credentials. Then you select a databse. Then you execute a query and result is assigned to $q. Next what i seen is that result is in ArrayCollection type (i saw it in xampp console) so i think we are converting it into Array while iterating through collection(I am not quite sure so if u know then please share). Then You are just encoding the result into JSON.

Now lets see how we will decode the JSON at our android program. Code looks like this:

void parseJSON()
    {
    	
    	String result = "";
    	String x = "";
    	InputStream is=null;
    	//http post
    	try{
    			ArrayList nameValuePairs = new ArrayList();
    	        HttpClient httpclient = new DefaultHttpClient();
    	        HttpPost httppost = new HttpPost("http://localhost/game_php_testing/android_database.php");
    	        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    	        HttpResponse response = httpclient.execute(httppost);
    	        HttpEntity entity = response.getEntity();
    	        is = entity.getContent();
    	}catch(Exception e){
    	        Log.e("log_tag", "Error in http connection "+e.toString());
    	}
    	//convert response to string
    	try{
    		 	
    	        BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
    	        StringBuilder sb = new StringBuilder();
    	        String line = null;
    	        while ((line = reader.readLine()) != null) {
    	                sb.append(line + "\n");
    	        }
    	        is.close();
    	 
    	        result=sb.toString();
    	        
    	}catch(Exception e){
    	        Log.e("log_tag", "Error converting result "+e.toString());
    	}
    	 

//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i catch(JSONException e){ Log.e(“log_tag”, “Error parsing data “+e.toString()); } }

I faced two problems/exception while connecting to php. PHP was connecting to mysql perfectly as when i run in browser it printed results so there was some issues on my above code which i’l address here and this is common problems which will be faced by every newcomer to android like me :D. Before that i’l just explain my php file and localhost path setup. When i installed xampp, in xampp folder there must be folder called htDocs so i have to make a project folder here inside htDocs and inside this project folder will be my php. So my php path would look like this “/htDocs/game_php_testing/android_database.php” So when i will make a call to php via “http://localhost/game_php_testing/android_database.php”

Now i will address the two problems that i faced.
First,

java.net.socketexception -permission denied

yes whenever i was trying to call my php i was getting this exception. How did i solved it ??? Well i just provided a permission to internet access at AndroidManifest.xml file. You have to put this permission above tag


Now second Problem, this one is very important.

java.net.ConnectException -Connection Refused.

Well what i found is that when u call localhost android thinks that u r calling to android emulator itself not the localhost machine. So localhost/127.0.0.1 wouldn’t work. So i found the solution to that: instead of localhost use 10.0.2.2, code will be like this:

HttpPost httppost = new HttpPost("http://10.0.2.2/game_php_testing/android_database.php");

Well problem solved :D. Now i decode the json that i got from php. I am printing the result on LOG. Please see that when i am calling “json_data.getString(“Player_name”)“, Player_name is a column/attribute in my database table and its type is varchar so i used getString() on it.

I hope this post helped you as you may also faced similar problem at first time.

Gracias.