Translate text with ML Kit on Android

This post is about how to setup ML Kit’s translation feature in Android application with the help of simple demo app.
 

Creating new project

1 . Create a new project by going to File  New Android Project, select Empty Activity , provide app name, select language to kotlin and then finally click on finish.

Adding Dependency

2 . Open build.gradle (Module: app) file and add the ML Kit’s Translation API dependency inside the dependencies section:

build.gradle

dependencies {
//ml kit translation API
implementation 'com.google.mlkit:translate:16.1.2'
}
Creating Layout File

3. The activity_main.xml layout file defines the UI of the application.

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
tools:context=".MainActivity">

<TextView
android:id="@+id/tv_from_english"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="From English"
android:textColor="@color/purple_700"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />

<EditText
android:id="@+id/edt_source_lang_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Enter English text"
android:textSize="18sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="@+id/tv_from_english"
app:layout_constraintTop_toBottomOf="@+id/tv_from_english" />

<TextView
android:id="@+id/tv_to_hindi"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:text="To Hindi"
android:textColor="@color/purple_700"
android:textSize="20sp"
android:textStyle="bold"
app:layout_constraintStart_toStartOf="@+id/edt_source_lang_text"
app:layout_constraintTop_toBottomOf="@+id/edt_source_lang_text" />

<TextView
android:id="@+id/tv_target_lang_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:hint="Hindi Translation"
android:textSize="20sp"
app:layout_constraintStart_toStartOf="@+id/tv_to_hindi"
app:layout_constraintTop_toBottomOf="@+id/tv_to_hindi" />

<ProgressBar
android:id="@+id/progressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:padding="10dp"
android:visibility="gone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_target_lang_text" />

<Button
android:id="@+id/btn_translate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:padding="10dp"
android:text="Translate"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tv_target_lang_text" />

</androidx.constraintlayout.widget.ConstraintLayout>
Writing MainActivity Code

4 . To translate a string between two languages create a Translator object, configure it with the source and target languages.

val options = TranslatorOptions.Builder()
.setSourceLanguage(TranslateLanguage.ENGLISH)
.setTargetLanguage(TranslateLanguage.HINDI)
.build()

val englishHindiTranslator = Translation.getClient(options)

5 . Next, we need to ensure that the model has been downloaded before running the translate() method. 

//Downloads the model files required for translation, if they are not already present
englishHindiTranslator.downloadModelIfNeeded()
.addOnSuccessListener {
Log.e(TAG, "Download Successful")
}
.addOnFailureListener {
Log.e(TAG, "Download Error: " + it.printStackTrace().toString())
}

Note: Avoid keeping too many language models (Its around 30MB) on the device at once (delete unneeded models) ,to prevent filling device memory.

5 . Once the model has downloaded successfully, pass a string of text in the source language to translate().

//Translates the given input from the source language into the target language.
englishHindiTranslator.translate(edtSourceLangText.text.toString())
.addOnSuccessListener {
//set translated text in textview
tvTargetLangText.setText(it)
}
.addOnFailureListener {
//Error
Log.e(TAG, "Error: " + it.localizedMessage.toString())
}
  • The translated text, in the target language you configured, is passed to the success listener.
  • In case of error, exception is passed to the failure listener.

6 . Ensure that the close() method is called when the Translator object will no longer be used. To do this on the Fragment or AppCompatActivity, we need to write the below code.

val englishHindiTranslator = Translation.getClient(options)
getLifecycle().addObserver(englishHindiTranslator)
Complete MainActivity code

MainActivity.kt

class MainActivity : AppCompatActivity() {

private val TAG = MainActivity::class.java.simpleName

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)

val edtSourceLangText: EditText = findViewById(R.id.edt_source_lang_text)
val tvTargetLangText: TextView = findViewById(R.id.tv_target_lang_text)
val btnTranslate: Button = findViewById(R.id.btn_translate)
val progressBar: ProgressBar = findViewById(R.id.progressBar)

val options = TranslatorOptions.Builder()
.setSourceLanguage(TranslateLanguage.ENGLISH)
.setTargetLanguage(TranslateLanguage.HINDI)
.build()

val englishHindiTranslator = Translation.getClient(options)
getLifecycle().addObserver(englishHindiTranslator)

btnTranslate.setOnClickListener({

//make sure that our EditText is not empty
if (!edtSourceLangText.text.isEmpty()) {

progressBar.visibility = View.VISIBLE
btnTranslate.visibility = View.GONE

//Downloads the model files required for translation, if they are not already present englishHindiTranslator.downloadModelIfNeeded()
.addOnSuccessListener {
Log.e(TAG, "Download Successful")
progressBar.visibility = View.GONE
btnTranslate.visibility = View.VISIBLE

//Translates the given input from the source language into the target language.
englishHindiTranslator.translate(edtSourceLangText.text.toString())
.addOnSuccessListener {
//Translation successful
tvTargetLangText.setText(it)
}
.addOnFailureListener {
//Error
Log.e(TAG, "Error: " + it.localizedMessage)
}
}
.addOnFailureListener {
Log.e(TAG, "Download Error: " + it.localizedMessage)
progressBar.visibility = View.GONE
btnTranslate.visibility = View.VISIBLE
}
}
})
}
Run the App

When you run the app it will look like this:

 

 

Leave a Reply