ZOFTINO.COM android and web dev tutorials

Android Translate Text Example

This post shows how to translate text between languages with an example. The example uses Firebase ML kit language translation API.

Android Translate Text Example

The example has one screen which allows user to enter text in any language and submit for translating it to English. The submit button’s event handler in the activity associated with the screen starts the translation process.

First it identifies the language of the text using Firebase language identification API. If it can’t identify the language, it will display a message. Once language of the entered text is identified, it will translate the text into English and display the translated text on the screen.

android translate text example

Project Setup

First make your project ready for building app features with Firebase APIs by following Firebase setup instructions.

Then add following dependencies to gradle build file.

    implementation 'com.google.firebase:firebase-core:17.0.0'
    implementation 'com.google.firebase:firebase-ml-natural-language:21.0.1'
    implementation 'com.google.firebase:firebase-ml-natural-language-language-id-model:20.0.4'
    implementation 'com.google.firebase:firebase-ml-natural-language-translate-model:20.0.4'
    implementation 'com.google.android.material:material:1.0.0-alpha1'

Firebase ML Kit Language Translation API

To translate text from source language to target language, first you need to create FirebaseTranslator object by calling getTranslator() method on FirebaseNaturalLanguage instance and passing translator options to the method.

FirebaseTranslatorOptions object can be created using FirebaseTranslatorOptions.Builder by specifying source and target languages.

FirebaseTranslatorOptions options =
        new FirebaseTranslatorOptions.Builder()
                .setSourceLanguage(FirebaseTranslateLanguage.ES)
                .setTargetLanguage(FirebaseTranslateLanguage.EN)
                .build();
final FirebaseTranslator Translator =
        FirebaseNaturalLanguage.getInstance().getTranslator(options);

Then call translate() method on FirebaseTranslator object passing input-text to it. Then add listeners to the resulting task. In the success listener, translated text can be obtained.

translator.translate(inputText)
      .addOnSuccessListener(
          new OnSuccessListener<String>() {
            @Override
            public void onSuccess(@NonNull String translatedText) {
              //do something with the translated text
            }
          })
      .addOnFailureListener(
          new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
		//do somthing in failure scenario
            }
     });

But before calling translate() method on FirebaseTranslator object, translation model for the languages need to be downloaded.

Translation models can be downloaded when needed or ahead of translations.

To make sure required language models exist before a translation, you need to call downloadModelIfNeeded() method on FirebaseTranslator object before calling translate().

You can specify download conditions, such as using wifi, when device is charging and when device is idle, using FirebaseModelDownloadConditions object.

FirebaseModelDownloadConditions fmdc = 
	new FirebaseModelDownloadConditions.Builder()
    .requireWifi()
    .build();

translator.downloadModelIfNeeded(fmdc)
      .addOnSuccessListener(
		...
          })
      .addOnFailureListener(
		...
          });

You can provide options in the app to manage language models using FirebaseTranslateModelManager. You can get a list downloaded models by calling getAvailableModels(), delete a model by calling deleteDownloadedModel() and download a model by calling downloadRemoteModelIfNeeded() on FirebaseTranslateModelManager object.

//get downloaded models
FirebaseTranslateModelManager modelManager = 
	FirebaseTranslateModelManager.getInstance();

modelManager.getAvailableModels(FirebaseApp.getInstance())


//delete downloaded model
FirebaseTranslateRemoteModel frModel =
        new FirebaseTranslateRemoteModel.Builder(
	FirebaseTranslateLanguage.FR).build();

modelManager.deleteDownloadedModel(frModel)


//download a model
FirebaseModelDownloadConditions fmdc = 
       new FirebaseModelDownloadConditions.Builder()
        .requireWifi()
	.requireCharging()
        .build();
FirebaseTranslateRemoteModel esModel =
        new FirebaseTranslateRemoteModel
		.Builder(FirebaseTranslateLanguage.ES)
                .setDownloadConditions(fmdc)
                .build();
modelManager.downloadRemoteModelIfNeeded(esModel)

Activity

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.google.android.gms.tasks.OnFailureListener;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions;
import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage;
import com.google.firebase.ml.naturallanguage.languageid.FirebaseLanguageIdentification;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions;

public class TranslateTextActivity extends AppCompatActivity {
    EditText text;
    TextView englishText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_translate_text);

        text = findViewById(R.id.enter_text);
        englishText = findViewById(R.id.translatedText);
    }

    public void translate(View v) {
        translateTextToEnglish(text.getText().toString());
    }

    public void translateText(FirebaseTranslator langTranslator) {
        //translate source text to english
        langTranslator.translate(text.getText().toString())
                .addOnSuccessListener(
                        new OnSuccessListener<String>() {
                            @Override
                            public void onSuccess(@NonNull String translatedText) {
                                englishText.setText(translatedText);
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Toast.makeText(TranslateTextActivity.this,
                                        "Problem in translating the text entered",
                                        Toast.LENGTH_LONG).show();
                            }
                        });

    }

    public void downloadTranslatorAndTranslate(String langCode) {
        //get source language id from bcp code
        int sourceLanguage = FirebaseTranslateLanguage
                .languageForLanguageCode(langCode);

        //create translator for source and target languages
        FirebaseTranslatorOptions options =
                new FirebaseTranslatorOptions.Builder()
                        .setSourceLanguage(sourceLanguage)
                        .setTargetLanguage(FirebaseTranslateLanguage.EN)
                        .build();
        final FirebaseTranslator langTranslator =
                FirebaseNaturalLanguage.getInstance().getTranslator(options);

        //download language models if needed
        FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder()
                .requireWifi()
                .build();
        langTranslator.downloadModelIfNeeded(conditions)
                .addOnSuccessListener(
                        new OnSuccessListener<Void>() {
                            @Override
                            public void onSuccess(Void v) {
                                Log.d("translator", "downloaded lang  model");
                                //after making sure language models are available
                                //perform translation
                                translateText(langTranslator);
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Toast.makeText(TranslateTextActivity.this,
                                        "Problem in translating the text entered",
                                        Toast.LENGTH_LONG).show();
                            }
                        });
    }

    public void translateTextToEnglish(String text) {
        //First identify the language of the entered text
        FirebaseLanguageIdentification languageIdentifier =
                FirebaseNaturalLanguage.getInstance().getLanguageIdentification();
        languageIdentifier.identifyLanguage(text)
                .addOnSuccessListener(
                        new OnSuccessListener<String>() {
                            @Override
                            public void onSuccess(@Nullable String languageCode) {
                                if (languageCode != "und") {
                                    Log.d("translator", "lang "+languageCode);
                                    //download translator for the identified language
                                    // and translate the entered text into english
                                    downloadTranslatorAndTranslate(languageCode);
                                } else {
                                    Toast.makeText(TranslateTextActivity.this,
                                            "Could not identify language of the text entered",
                                            Toast.LENGTH_LONG).show();
                                }
                            }
                        })
                .addOnFailureListener(
                        new OnFailureListener() {
                            @Override
                            public void onFailure(@NonNull Exception e) {
                                Toast.makeText(TranslateTextActivity.this,
                                        "Problem in identifying language of the text entered",
                                        Toast.LENGTH_LONG).show();
                            }
                        });
    }
}

Activity Layout

<?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"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        android:text="Translate Text to English"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/enter_text_l"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="16dp"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/title"
        android:hint="Enter Text">
        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/enter_text"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </com.google.android.material.textfield.TextInputLayout>
    <TextView
        android:id="@+id/translatedText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:textAppearance="@style/TextAppearance.AppCompat.Large"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/enter_text_l"/>
    <Button
        android:id="@+id/translate"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:text="Traslate to English"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/translatedText"
        android:onClick="translate"
        style="@style/Widget.AppCompat.Button.Colored"/>
</androidx.constraintlayout.widget.ConstraintLayout>