How to build an Android Language Translator App - Hive Programmers
Greetings to my favorite science community online, StemSocial.
It's @skyehi and I'm always happy to be back to continue my series on Android App development tutorial for beginners.
As our world grows with more people from different backgrounds and with different native languages trying to communicate online, language translators become very important.
There are so many language translators out there including Google Translator and popular ones like Deepl Translator.
To continue our progress in developing Android Apps and improving our programming skills, we'll be building a language translator Android app in today's tutorial.
I really hope you're excited guys, although it wouldn't be too complicated an app since it's a beginner's tutorial, we'll learn a lot trying to build this App. - Let's get started with our project shall we.
Original Image Source by lmonk72 from Pixabay
Setting up a new Android Studio project
Those that have been following my series will probably be very used to this first step but for the benefit of newcomers, I'll always include it.
To begin building our language translator app, we would need to ensure that Android Studio and Java Development Kit, JDK are properly installed on your Computer.
Please share in the comments section your concerns or issues in trying to install any of these softwares.
If you're ok with that step, the first thing we would be doing is opening the Android Studio software and creating a new Android Studio project with an Empty Activity.
Adding dependencies
I promised that awe would be learning some new stuff right. Well there are dependencies in Android App development. These dependencies allow the Android Studio platform to recognize and use certain services and APIs.
Adding dependencies will be done in the build.gradle
file. So guys locate that file which is usually at the bottom left side menu of your Android Studio software. Open it and add the following code;
Here is the dependency to add to the gradle file
implementation 'com.google.android.gms:play-services-translate:16.1.0'
implementation 'com.android.volley:volley:1.2.1'
The moment you start making changes to the build.gradle
file, a sync button will appear at the top of your screen. After you're done writing the dependency code, click on the sync button for your project to apply the changes.
Designing the User Interface
It's now time for us to work on the frontend of our App. Like I mentioned earlier, it wouldn't be too complex an app with lots of different features.
We'll build a very simple and basic language translator App with an EditText
for input, a Spinner
for selecting languages, and a TextView
to display the translated text.
As we advance and make more progress, we'll build more complex applications and be using other advanced user interface tools like Flutter.
Here's how the code should look like
(html comment removed: activity_main.xml )
<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:orientation="vertical"
android:padding="16dp"
tools:context=".MainActivity">
<EditText
android:id="@+id/editTextInput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter text to translate"/>
<Spinner
android:id="@+id/spinnerLanguages"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"/>
<Button
android:id="@+id/buttonTranslate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Translate"/>
<TextView
android:id="@+id/textViewTranslation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:textSize="18sp"/>
</LinearLayout>
Handling The Translation Logic
Alright guys, just like we did in the previous blog, I'll be sharing a very long code for the backend. This is the part where we build the translation logic. We'll be using a lot of different classes, we'll also call and override a lot of methods as well.
All the codes should work fine if you were able to successfully add the Google translate dependency in build.gradle
file. If you're having trouble with writing the code or you seem to be receiving errors when syncing the dependency, please let me know in the comments section below.
The translation logic of our App will be handled in MainActivity.java
file using the Google Translate API. Alright guys, I hope you're ready for the marathon.
Here's how your code should look like
// MainActivity.java
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.android.gms.tasks.OnSuccessListener;
import com.google.android.gms.tasks.Task;
import com.google.android.gms.tasks.Tasks;
import com.google.mlkit.nl.translate.TranslateLanguage;
import com.google.mlkit.nl.translate.TranslateOptions;
import com.google.mlkit.nl.translate.Translation;
import com.google.mlkit.nl.translate.Translator;
import com.google.mlkit.nl.translate.TranslatorOptions;
// Inside the MainActivity class
private EditText editTextInput;
private Spinner spinnerLanguages;
private Button buttonTranslate;
private TextView textViewTranslation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTextInput = findViewById(R.id.editTextInput);
spinnerLanguages = findViewById(R.id.spinnerLanguages);
buttonTranslate = findViewById(R.id.buttonTranslate);
textViewTranslation = findViewById(R.id.textViewTranslation);
// Initialize the languages in the spinner (you can replace this with your preferred list)
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this,
R.array.languages_array,
android.R.layout.simple_spinner_item
);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerLanguages.setAdapter(adapter);
buttonTranslate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
translateText();
}
});
}
private void translateText() {
String inputText = editTextInput.getText().toString();
String sourceLanguage = TranslateLanguage.ENGLISH; // or use auto-detection
String targetLanguage = getSelectedLanguageCode();
TranslatorOptions options = new TranslatorOptions.Builder()
.setSourceLanguage(sourceLanguage)
.setTargetLanguage(targetLanguage)
.build();
Translator translator = Translation.getClient(options);
Task<String> downloadModel = translator.downloadModelIfNeeded();
Tasks.whenAllComplete(downloadModel)
.addOnSuccessListener(new OnSuccessListener<List<Task<?>>>() {
@Override
public void onSuccess(List<Task<?>> tasks) {
Task<String> translationTask = translator.translate(inputText);
translationTask.addOnSuccessListener(new OnSuccessListener<String>() {
@Override
public void onSuccess(String translation) {
textViewTranslation.setText(translation);
}
});
}
});
}
private String getSelectedLanguageCode() {
// Retrieve the language code based on the selected language in the spinner
// You can replace this with a more robust language code retrieval method
return "es"; // Example: Spanish
}
Adding Language Codes
Now guys, for our App to work effectively, we need to define the language codes and that would be done inside the res/values/arrays.xml
file. Include your supported languages. You will be deciding which languages your App will support Translation.
I would recommend including every language so that if you publish your App, anyone from anywhere can use it. However to make things simple for first timers, I'll stick to two languages. You can add more if you wish to guys.
Here's how your code should look like
<resources>
<string-array name="languages_array">
<item>English</item>
<item>Spanish</item>
(html comment removed: Add more languages as needed )
</string-array>
</resources>
Requesting Internet Permission in Android Manifest
Now guys, we should not forget to add the internet permission to our App. Since our App would need to access internet service in order to utilize the Google API to perform language translations, we need to request internet Permission in AndroidManifest.xml
Here's how your code should look like;
package="your.package.name">
<uses-permission android:name="android.permission.INTERNET" />
<application
(html comment removed: ... other application elements ... )
>
(html comment removed: ... activities, services, etc. ... )
</application>
</manifest>
Running The App
That's all for now guys. We have successfully built a basic Language Translator on Android. It's time to run the App and you have two choices as usual. You can either run the App on a physical Android device which is usually my personal choice or you can run the App on an emulator.
When your App, opens, you can type a sentence and choose which language to translate it into using the spinner.
Thank you so much for taking the time to read today's blog guys. I hope you enjoyed the tutorial. We're getting closer and closer to building more complex applications.
As always, if you're having trouble writing the code, syncing the dependency or running the App, let me know in the comments section guys.
Have a lovely day and catch you next time on StemSocial. Goodbye 👨💻
You Can Follow Me @skyehi For More Like This And Others
Thanks for your contribution to the STEMsocial community. Feel free to join us on discord to get to know the rest of us!
Please consider delegating to the @stemsocial account (85% of the curation rewards are returned).
Thanks for including @stemsocial as a beneficiary, which gives you stronger support.