In my previous article, I described how to enable multi-lingual support for your android application which uses just static text. You can find it here

But most of the applications don’t just have static text. We have some text that comes from the backend as well. In this article, I’ll tell three different ways to translate the dynamic text. You can choose any one of them depending on your need. For me the third method worked well.

Google Translation API

GCP offers Translation Service. Some of its advantages are:

🟢 Its easy to implement

🟢 You can buy plan according to your need. It has two services one for basic translations and other for advanced translations.

🟢 Since the models are remotely hosted in Google Cloud, the translation quality is also good.

Some of its disadvantages are:

🔴 💵It becomes costly if you implement it in many places inside your app.

🔴 Since the models are remotely hosted, it requires internet for translation to happen.

When is it best to use this: Its best to use in activities where you require high quality translation and such activities are less visited by the user.

You can read this article to know how to use the service: https://medium.com/@yeksancansu/how-to-use-google-translate-api-in-android-studio-projects-7f09cae320c7

Another way to implement translation is through your backend. This means that the client sends the language code in which it wants the data. The server returns the text in the requested language. Some of the advantages of using this strategy are:

🟢 Its very easy to implement in both frontend and the backend. In frontend, you can store the language in the SharedPreferences and access it when needed.

🟢 Its cost effective in comparison to the previous method. This is because in google translation API, the billing is done on the basis of each translation. This means that if the user opens a certain activity 10 times, the translation will be done 10 times. But when the backend returns the translated text, the cost is required only to store the extra columns for different languages. Doesn’t matter how many times users open that activity, the cost will not grow and remain the same.

Some of the disadvantages of this strategy are:

🔴 💵The cost increases if you have large texts, too many rows or too many alternative languages.

Src:https://developers.google.com/ml-kit/language/translation

This is a complete different approach from the above two. Because this time the translation is done on client’s device only.

The first time translation is done, the model is downloaded on the client’s device. After that the translation can be done without any internet. This seems to be best 👍. But it isn’t. Just like other methods, this also has some disadvantages:

🔴 The translation quality is not very good when it comes to translating bigger texts.

🔴 The translation models are translated to and from English, i.e, if you want to translate from French to German, the text is first translated from French to English and then from English to German. This further reduces the translation quality for non-english languages.

🔴 You’ll have to adhere to some guidelines made by google like branding, etc. Read more about it here

Src:https://cloud.google.com/translate/attribution

Now lets see how to use the API:

The API is very easy to implement. You can see the documentation here.

Step 1️⃣ : Language Identification

This step is optional and depends on your need. In this step, we’ll identify the input language or the language coming from the server. Its good if we know our source language, otherwise we can apply this step to know it.

Add dependency in build.gradle (app level)

implementation 'com.google.mlkit:language-id:16.1.1'

Now add following code in your activity/fragment:

val languageIdentifier=LanguageIdentification.getClient()
binding.button.setOnClickListener {
languageIdentifier.identifyLanguage(binding.editText.text.toString())
.addOnCompleteListener {
if(it.isSuccessful)
{
if(it.result!=null)
{
if(it.result!="und" && TranslateLanguage.fromLanguageTag(it.result!!)!=null)
{
Log.d("div","Translate L35 ${it.result} ${TranslateLanguage.fromLanguageTag(it.result!!)}")
binding.textViewCurrentLanguage.text=it.result
translate(binding.editText.text.toString(), TranslateLanguage.fromLanguageTag(it.result!!)!!)
}
else
binding.textViewCurrentLanguage.text="Undefined Language"
}
else
binding.textViewCurrentLanguage.text="null"
}
else
{
binding.textViewCurrentLanguage.text="Error ${it.exception}"
Log.d("div","Identification Task Failed ${it.exception}")
}
}
}

The language identifier API returns “und” for undefined language otherwise it returns the language code.

Step 2️⃣ : Translate the text

Now we’ll call the translate function as follows:

private fun translate(text: String, fromLang: String) {
val options=TranslatorOptions.Builder()
.setSourceLanguage(fromLang)
.setTargetLanguage(toLang)
.build()
val translator=Translation.getClient(options)

val conditions=DownloadConditions.Builder()
.build() //You can provide conditions like wifi and charging here
translator.downloadModelIfNeeded(conditions)
.addOnCompleteListener { it1 ->
if(it1.isSuccessful)
{
Toast.makeText(requireContext(),"Translation model downloaded successfully",Toast.LENGTH_LONG).show()
translator.translate(text)
.addOnCompleteListener {
if(it.isSuccessful)
{
binding.textView.text=it.result
Log.d("div","Translation successful ${it.result}")
}
else
{
Toast.makeText(requireContext(),"Translation failed",Toast.LENGTH_LONG).show()
Log.d("div","Translation Task failed ${it.exception}")
}
}
}
else
{
Toast.makeText(requireContext(),"Translation model couldn't be downloaded",Toast.LENGTH_LONG).show()
Log.d("div","Translation Download Task failed ${it1.exception}")
}
}
}

Here in the code, we firstly made a client for translation.

Then we downloaded the model if needed. The Translation API does it itself using the DownloadManager. Once the model is downloaded, the translation can be done without any internet.

Just that and congratulations you have successfully added multi language support to your app with dynamic text. 🥳

For full code, see this repositoryhttps://github.com/divyanshutw/MLKit_NLP

Githubhttps://github.com/divyanshutw

LinkedInhttps://www.linkedin.com/in/divyanshu-tiwari-7a7318173

👨‍💻 Android Developer||Java is ❤||Fond of Problem Solving||SSB Recommended