Integrate Google Translate API to your Android App

Actually, this post was originally published on my old blog site then I decided to transfer it in here my personal website since I didn’t maintain that site at all.

This Tutorial is intended for developers who want to write their own mobile applications that can interact with the Google Translate API.

In order to access Google Translate API, you need to first create a project in Google Developers Console

Integrate Google Translate API

Click Create a project and name it as what you desire and click Create Button
I recommend you to name it as same as your mobile app project.
Now, let’s move to the next step.

Integrate Google Translate API

Google Translate API is not free, you need to enable your billing account before you can start using it.

The pricing of Google Translate API is based on what you use.

“Translation usage is calculated in millions of characters (M), where 1 M = 106 characters.

-Google

Now click on your project and select Billing & Settings. in the sidebar on the left and then select Enable billing.

Integrate Google Translate API

Set up your billing profile, select a country and click confirm button then fill out the form, and click Submit and enable billing.

Integrate Google Translate API

Now your billing account has been enabled. Let’s move into the real process.

Your application request that sends into Google Translate API must identify your application to Google based on unique key or API key. You have to generate a SHA-1 key to be able to generate the API key dedicated to your application. But I will show you first how to integrate Google Translate API into your app step by step.

After you have successfully enabled your billing account.
You need to enable the Google Translate API by clicking APIs & Auth, select APIs and search for google translate then click the OFF button to turn it ON.

Integrate Google Translate API

after that, Select Credentials in the sidebar on the left under the APIs button and click

Create New Key.

Integrate Google Translate API

A pop-up dialog will be shown.

then select Browser Key.

Integrate Google Translate API

And leave the text box as blank and select Create Button.

Integrate Google Translate API

Now you can see that the API Key has been created. Leave it for now, we will use it later in this tutorial. Let’s move into the coding part \m/

Integrate Google Translate API

Now open your android development tools like Android Studio or Eclipse and select your existing project or create a new one. I will suggest you use Android Studio instead of eclipse.
Visit this link if you want to know more about Android Studio.

First, add GSON library into your project
You can download it from here GSON Download
and import the Jar file into your project if you are using eclipse and add this line to your build.gradle file if you are using Android Studio then clean the project.

[pre] dependencies { compile ‘com.google.code.gson:gson:2.2.4’ } [/pre]
After that create a new class to retrieve data after your request it coming from Google Translate API.
Name it as GoogleTranslateActivity.java and copy the code below and paste it into your class.
[pre]
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.JsonSyntaxException;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import javax.net.ssl.HttpsURLConnection;
/**
*
*/
public class GoogleTranslate {

private String key;

public GoogleTranslate(String apiKey) {
key = apiKey;
}

public GoogleTranslate() {

}

String translte(String text, String from, String to) {
StringBuilder result = new StringBuilder();
try {
String encodedText = URLEncoder.encode(text, “UTF-8”);
String urlStr = “https://www.googleapis.com/language/translate/v2?key=” + key + “&q=” + encodedText + “&target=” + to + “&source=” + from;

URL url = new URL(urlStr);

HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
InputStream stream;
if (conn.getResponseCode() == 200) //success
{
stream = conn.getInputStream();
} else
stream = conn.getErrorStream();

BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}

JsonParser parser = new JsonParser();

JsonElement element = parser.parse(result.toString());

if (element.isJsonObject()) {
JsonObject obj = element.getAsJsonObject();
if (obj.get(“error”) == null) {
String translatedText = obj.get(“data”).getAsJsonObject().
get(“translations”).getAsJsonArray().
get(0).getAsJsonObject().
get(“translatedText”).getAsString();
return translatedText;

}
}

if (conn.getResponseCode() != 200) {
System.err.println(result);
}

} catch (IOException | JsonSyntaxException ex) {
System.err.println(ex.getMessage());
}

return null;
}
public static void main(String[] args) {

GoogleTranslate translator = new GoogleTranslate(“YOUR_API_KEY”);//change it to your own apikey generated by google

System.out.println(text);
}
[/pre]
After that, create a new XML file and copy the code below.

<relativelayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#c6c6c6"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:id="@+id/translatabletext"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:text="Hi, Translate Me!"
        android:textSize="25sp" />

    <EditText
        android:id="@+id/translateedittext"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_below="@+id/translatabletext"
        android:layout_centerHorizontal="true"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="20dp"
        android:background="@android:color/white"
        android:hint="English - Tagalog"
        android:padding="5dp" />

    <Button
        android:id="@+id/translatebutton"
        android:layout_width="match_parent"
        android:layout_height="40dp"
        android:layout_below="@+id/translateedittext"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="20dp"
        android:textStyle="bold"
        android:text="Translate" />

</RelativeLayout>

Create a new class and set the XML we created with the view.
This class will serve as our Main Activity which contains the function and the interface of the app for user activities.

copy the code below and paste it into your class.
[pre]
import android.support.v7.app.ActionBarActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
GoogleTranslateMainActivity translator;
EditText translateedittext;
TextView translatabletext;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
translateedittext = (EditText) findViewById(R.id.translateedittext);
Button translatebutton = (Button) findViewById(R.id.translatebutton);
translatebutton.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
new EnglishToTagalog().execute();

}
});
}

private class EnglishToTagalog extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;

protected void onError(Exception ex) {

}
@Override
protected Void doInBackground(Void… params) {

try {
translator = new GoogleTranslateMainActivity(“YOUR_API_KEY”);

Thread.sleep(1000);

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;

}
@Override
protected void onCancelled() {
super.onCancelled();
}

@Override
protected void onPreExecute() {
//start the progress dialog
progress = ProgressDialog.show(MainActivity.this, null, “Translating…”);
progress.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progress.setIndeterminate(true);
super.onPreExecute();
}
@Override
protected void onPostExecute(Void result) {
progress.dismiss();

super.onPostExecute(result);
translated();
}

@Override
protected void onProgressUpdate(Void… values) {
super.onProgressUpdate(values);
}

}

public void translated(){

String translatetotagalog = translateedittext.getText().toString();//get the value of text
String text = translator.translte(translatetotagalog, “en”, “tl”);
translatabletext = (TextView) findViewById(R.id.translatabletext);
translatabletext.setText(text);

}

}[/pre]

Don’t forget to check the Manifest.xml file, you must add the activity what we created earlier and set the permission

<uses-permission android:name=“android.permission.INTERNET” />
<uses-permission android:name=“android.permission.ACCESS_NETWORK_STATE” />

the app will force close if you not add it into manifest.

congratulation. You have successfully integrated Google Translate API to your app.

Download the Source code here

Leave a Comment

Your email address will not be published. Required fields are marked *