Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

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

  • Last Updated : 28 Nov, 2021

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 German language. After clicking that button our text will be translated to the German language which we can get to see in the text view. A sample video is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 

Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready.



Step by Step Implementation

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. Note that select Java as the programming language.

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 file.  

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

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



// dependency for firebase core.

implementation’com.google.firebase:firebase-core:15.0.2′

// below two dependency are used for language detection

implementation ‘com.google.firebase:firebase-ml-natural-language:22.0.0’

implementation ‘com.google.firebase:firebase-ml-natural-language-translate-model:20.0.8’

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

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

XML




<!--permission for internet-->
<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. 



XML




<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
  
    <!--edit text to enter your input-->
    <EditText
        android:id="@+id/idEdtLanguage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="50dp"
        android:hint="Enter your name to translate"
        android:padding="4dp"
        android:textColor="@color/black"
        android:textSize="20sp" />
  
    <!--button to translate language of the input text-->
    <Button
        android:id="@+id/idBtnTranslateLanguage"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/idTVTranslatedLanguage"
        android:layout_centerInParent="true"
        android:text="Translate language" />
  
    <!--text view to display the translated text-->
    <TextView
        android:id="@+id/idTVTranslatedLanguage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/idEdtLanguage"
        android:layout_centerHorizontal="true"
        android:layout_margin="20dp"
        android:gravity="center_horizontal"
        android:text="Translated language"
        android:textAlignment="center"
        android:textSize="20sp" />
      
</RelativeLayout>

Step 6: Working with the MainActivity.java file

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

Java




import android.os.Bundle;
import android.view.View;
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.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.translate.FirebaseTranslateLanguage;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslator;
import com.google.firebase.ml.naturallanguage.translate.FirebaseTranslatorOptions;
  
public class MainActivity extends AppCompatActivity {
  
    // creating variables for our image view, 
    // text view and two buttons.
    private EditText edtLanguage;
    private TextView translateLanguageTV;
    private Button translateLanguageBtn;
      
    // create a variable for our 
    // firebase language translator.
    FirebaseTranslator englishGermanTranslator;
  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
          
        // on below line we are creating our firebase translate option.
        FirebaseTranslatorOptions options =
                new FirebaseTranslatorOptions.Builder()
                        // below line we are specifying our source language.
                        .setSourceLanguage(FirebaseTranslateLanguage.EN)
                        // in below line we are displaying our target language.
                        .setTargetLanguage(FirebaseTranslateLanguage.DE)
                        // after that we are building our options.
                        .build();
        // below line is to get instance
        // for firebase natural language.
        englishGermanTranslator = FirebaseNaturalLanguage.getInstance().getTranslator(options);
  
        // on below line we are initializing our variables.
        edtLanguage = findViewById(R.id.idEdtLanguage);
        translateLanguageTV = findViewById(R.id.idTVTranslatedLanguage);
        translateLanguageBtn = findViewById(R.id.idBtnTranslateLanguage);
          
        // adding on click listener for button
        translateLanguageBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // calling method to download language 
                // modal to which we have to translate.
                String string = edtLanguage.getText().toString();
                downloadModal(string);
            }
        });
    }
  
    private void downloadModal(String input) {
        // below line is use to download the modal which
        // we will require to translate in german language
        FirebaseModelDownloadConditions conditions = new FirebaseModelDownloadConditions.Builder().requireWifi().build();
          
        // below line is use to download our modal.
        englishGermanTranslator.downloadModelIfNeeded(conditions).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void aVoid) {
                  
                // this method is called when modal is downloaded successfully.
                Toast.makeText(MainActivity.this, "Please wait language modal is being downloaded.", Toast.LENGTH_SHORT).show();
                 
                // calling method to translate our entered text.
                translateLanguage(input);
  
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(MainActivity.this, "Fail to download modal", Toast.LENGTH_SHORT).show();
            }
        });
    }
  
    private void translateLanguage(String input) {
        englishGermanTranslator.translate(input).addOnSuccessListener(new OnSuccessListener<String>() {
            @Override
            public void onSuccess(String s) {
                translateLanguageTV.setText(s);
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Toast.makeText(MainActivity.this, "Fail to translate", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

Now run your app and see the output of the app.

Output:

Note: When you are using the app for the first time. It will take some time because it will download the modal in the background. 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.  

Check out the project on the below link: https://github.com/ChinmayMunje/Firebase-ML-Kit




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!