How to Create Language Translator in Android using Firebase ML Kit?
Last Updated :
25 Mar, 2025
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.
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:
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
Similar Reads
Java Tutorial Java is a high-level, object-oriented programming language used to build web apps, mobile applications, and enterprise software systems. It is known for its Write Once, Run Anywhere capability, which means code written in Java can run on any device that supports the Java Virtual Machine (JVM).Java s
10 min read
Machine Learning Tutorial Machine learning is a branch of Artificial Intelligence that focuses on developing models and algorithms that let computers learn from data without being explicitly programmed for every task. In simple words, ML teaches the systems to think and understand like humans by learning from the data.It can
5 min read
Java Interview Questions and Answers Java is one of the most popular programming languages in the world, known for its versatility, portability, and wide range of applications. Java is the most used language in top companies such as Uber, Airbnb, Google, Netflix, Instagram, Spotify, Amazon, and many more because of its features and per
15+ min read
Java OOP(Object Oriented Programming) Concepts Java Object-Oriented Programming (OOPs) is a fundamental concept in Java that every developer must understand. It allows developers to structure code using classes and objects, making it more modular, reusable, and scalable.The core idea of OOPs is to bind data and the functions that operate on it,
13 min read
Arrays in Java Arrays in Java are one of the most fundamental data structures that allow us to store multiple values of the same type in a single variable. They are useful for storing and managing collections of data. Arrays in Java are objects, which makes them work differently from arrays in C/C++ in terms of me
15+ min read
Linear Regression in Machine learning Linear regression is a type of supervised machine-learning algorithm that learns from the labelled datasets and maps the data points with most optimized linear functions which can be used for prediction on new datasets. It assumes that there is a linear relationship between the input and output, mea
15+ min read
Inheritance in Java Java Inheritance is a fundamental concept in OOP(Object-Oriented Programming). It is the mechanism in Java by which one class is allowed to inherit the features(fields and methods) of another class. In Java, Inheritance means creating new classes based on existing ones. A class that inherits from an
13 min read
Support Vector Machine (SVM) Algorithm Support Vector Machine (SVM) is a supervised machine learning algorithm used for classification and regression tasks. It tries to find the best boundary known as hyperplane that separates different classes in the data. It is useful when you want to do binary classification like spam vs. not spam or
9 min read
Collections in Java Any group of individual objects that are represented as a single unit is known as a Java Collection of Objects. In Java, a separate framework named the "Collection Framework" has been defined in JDK 1.2 which holds all the Java Collection Classes and Interface in it. In Java, the Collection interfac
15+ min read
Java Exception Handling Exception handling in Java allows developers to manage runtime errors effectively by using mechanisms like try-catch block, finally block, throwing Exceptions, Custom Exception handling, etc. An Exception is an unwanted or unexpected event that occurs during the execution of a program, i.e., at runt
10 min read