Open In App

How to Create Language Translator in Android using Firebase ML Kit?

Last Updated : 25 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In the previous article, we have seen using Language detector in Android using Firebase ML kit. In this article, we will take a look at the implementation of Language translator in Android using Firebase ML Kit in Android

What we are going to build in this article? 

We will be building a simple application in which we will be showing an EditText field and we will add any input to that TextField. Along with that, we will be displaying a Button to translate that text to the Hindi language. After clicking that button our text will be translated which we can get to see in the text view.

Steps to Implement Language Translator in Android

Step 1: Create a New Project

To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio.

Step 2: Connect your app to Firebase

After creating a new project in Android Studio connect your app to Firebase. For connecting your app to firebase. Navigate to Tools on the top bar. After that click on Firebase. A new window will open on the right side. Inside that window click on Firebase ML and then click on Use Firebase ML kit in Android. You can see the option in the below screenshot.  

firebase-ml-kit

After clicking on this option you will get to see the below screen. On this screen click on Connect to Firebase option to connect your app to Firebase. Click on Connect option to connect your app to Firebase and add the below dependency to your build.gradle.kts file.  


Step 3: Adding dependency for language translation to build.gradle.kts file

Navigate to the Gradle Scripts > build.gradle.kts(Module:app) and add the below dependency in the dependencies section.   

dependencies {
...
implementation ("com.google.firebase:firebase-core:21.1.1")
implementation ("com.google.firebase:firebase-ml-natural-language:22.0.1")
implementation ("com.google.firebase:firebase-ml-natural-language-translate-model:20.0.9")
}


Step 4: Adding permissions to access the Internet in your Android App

Navigate to the app > manifests > AndroidManifest.xml file and add the below code to it. Comments are added in the code to get to know in more detail.  

<uses-permission android:name="android.permission.INTERNET"/>

Step 5: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 

activity_main.xml:

XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:gravity="center"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <EditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="64dp"
        android:autofillHints="none"
        android:hint="Enter text to translate"
        android:inputType="none"
        android:textColor="@color/black"
        android:textSize="20sp" />

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Translate" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="25dp"
        android:text="Translated language"
        android:textAlignment="center"
        android:textSize="20sp" />

</LinearLayout>

Design UI:

translate-design-ui


Step 6: Working with the MainActivity file

Go to the MainActivity file and refer to the following code. Below is the code for the MainActivity file. Comments are added inside the code to understand the code in more detail.

MainActivity File:

MainActivity.java
package org.geeksforgeeks.demo;

import android.os.Bundle;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions;
import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage;
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 MainActivity extends AppCompatActivity {

    private boolean isDownloaded = false;
    private EditText editText;
    private TextView textView;
    private Button button;
    
    // Firebase Language Translator
    private FirebaseTranslator translator; 

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

        // Firebase Translator Options
        FirebaseTranslatorOptions options = new FirebaseTranslatorOptions.Builder()
                .setSourceLanguage(FirebaseTranslateLanguage.EN) // Source language: English
                .setTargetLanguage(FirebaseTranslateLanguage.FR) // Target language: French
                .build();

        // Get Firebase Translator Instance
        translator = FirebaseNaturalLanguage.getInstance().getTranslator(options);

        editText = findViewById(R.id.editText);
        textView = findViewById(R.id.textView);
        button = findViewById(R.id.button);

        // Translator Button Click Listener
        button.setOnClickListener(view -> {
            String inputText = editText.getText().toString();
            if (!isDownloaded) {
                downloadModel(inputText);
            } else {
                translateText(inputText);
            }
        });
    }

    // Function to Download Target Language Model
    private void downloadModel(String inputText) {
        FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder()
                .requireWifi()
                .build();

        translator.downloadModelIfNeeded(conditions)
                .addOnSuccessListener(unused -> {
                    Toast.makeText(MainActivity.this, 
                            "Please wait, language model is downloading.", 
                            Toast.LENGTH_SHORT).show();
                    isDownloaded = true;
                    
                    // Translate after download
                    translateText(inputText); 
                })
                .addOnFailureListener(e -> {
                    Toast.makeText(MainActivity.this, "Download failed", Toast.LENGTH_SHORT).show();
                });
    }

    // Function to Translate User Input
    // and Display in TextView
    private void translateText(String inputText) {
        translator.translate(inputText)
                .addOnSuccessListener(translatedText -> textView.setText(translatedText))
                .addOnFailureListener(e -> 
                    Toast.makeText(MainActivity.this, "Failed to translate", Toast.LENGTH_SHORT).show());
    }
}
MainActivity.kt
@file:Suppress("DEPRECATION")

package org.geeksforgeeks.demo

import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.firebase.ml.common.modeldownload.FirebaseModelDownloadConditions
import com.google.firebase.ml.naturallanguage.FirebaseNaturalLanguage
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslateLanguage
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions


class MainActivity : AppCompatActivity() {
    private var isDownloaded = false
    private lateinit var editText: EditText
    private lateinit var textView: TextView
    private lateinit var button: Button

    // firebase language translator
    private lateinit var translator: FirebaseTranslator

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

        // creating firebase translate option.
        val options =
            FirebaseTranslatorOptions.Builder()
                // setting current language to english
                .setSourceLanguage(FirebaseTranslateLanguage.EN)
                
                // setting target language to french
                .setTargetLanguage(FirebaseTranslateLanguage.FR)
                .build()

        // get instance for firebase natural language translator
        translator = FirebaseNaturalLanguage.getInstance().getTranslator(options)

        editText = findViewById(R.id.editText)
        textView = findViewById(R.id.textView)
        button = findViewById(R.id.button)

        // translator button
        button.setOnClickListener {
            val string = editText.getText().toString()
            if(!isDownloaded) {
            
                // this downloads the target language modal
                downloadModal(string)
            } else {
            
                // directly translates if modal is already downloaded
                translateLanguage(string)
            }
        }
    }

    // function to download target language modal
    private fun downloadModal(input: String) {
        val conditions = FirebaseModelDownloadConditions.Builder().requireWifi().build()

        translator.downloadModelIfNeeded(conditions)
            .addOnSuccessListener {
            
                // downloaded successfully
                Toast.makeText(
                    this@MainActivity,
                    "Please wait language modal is being downloaded.",
                    Toast.LENGTH_SHORT
                ).show()
                
                // translates the user input to target language
                translateLanguage(input)
                isDownloaded = true
            }.addOnFailureListener {
            
                // download failed
                Toast.makeText(this@MainActivity, "Download failed", Toast.LENGTH_SHORT).show()
            }
    }

    // function to translate user input to
    // target language and display in textview
    private fun translateLanguage(input: String) {
        // translates
        translator.translate(input)
            .addOnSuccessListener { translatedText ->
                
                // displaying in textview
                textView.text = translatedText
            }
            .addOnFailureListener {
                Toast.makeText(this@MainActivity, "Fail to translate", Toast.LENGTH_SHORT).show()
            }
    }
}

Output:

Important: When you are using the app for the first time. It will take some time because it will download the modal in the background. 

Note: We are not adding multiple language support in this application because for each language we have to download the language conversion model so it will make the app heavier and language translation will take so much time.  

Refer to the following github repo for the entire code: Language_Translator_Android_Firebase


Next Article

Similar Reads