Friday, May 18, 2012

Using Google Translate API In Android

In this tutorial we are going to know how we can use google translate API in Android

At first download google-api-translate-java-0.95.jar here 


Import that JAR file to android buid Path (Right-click project->Properties->Java Build Path-> Libraries->Add External JARS.)

The xml file


main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView 
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="@string/hello"
    />
</LinearLayout>


The JAVA file 


Translator.java:


package com.myapps.translate;


import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.Toast;


import com.google.api.translate.Language;
import com.google.api.translate.Translate;


public class Translator extends Activity {
    /** Called when the activity is first created. */
String translatedText;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        TextView tv = new TextView(this);
        Translate t = new Translate();
        
        try {
translatedText = t.execute("Bonjour le monde", Language.FRENCH, Language.ENGLISH);


//tv.setText(translatedText);
        } catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


        Toast.makeText(this, translatedText, Toast.LENGTH_SHORT).show();
        
        tv.setText(translatedText);
        
        setContentView(tv);
    }
}