How to use Google Translate API in Android Studio projects?
Cansu Yeksan Aktaş
Mar 11, 2019 · 6 min read
Cloud Translate API is one of the most useful API which Google offers to developers. Implementation of Cloud Translate API to your project is really simple, so you can prefer to use it in your translation projects.
As we know, every beautiful thing has a price. Before implementing Cloud Translate API to your project, you can check the pricing from the link: https://cloud.google.com/translate/pricing
Important Note: The steps of getting c redentials file (in JSON format) from Cloud Translation API are going to be explained in detail until step 19. If you have already get the credentials file and want to see the implementation of the code, please just skip to the 19th step.
Both Java and Kotlin codes are included in this post.
Now, we are ready to start the implementation of Cloud Translate API to the project. Let’s start step by step:
- The first thing to do is to sign in Google API Console from the link: https://console.cloud.google.com/apis/
If you have a Google API Console account, enter your Email or phone, and your password.
If you do not have a Google API Console account, you can click on “ Create account” and start to create an account for Google API Console. Then, below page will appear:
After entering your personal information, you will be directed to your profile dashboard in the Google API Console. Check “ I accept the Google Platform Terms of Service and the terms of service for all applicable services and APIs.”
2. Click on the “ Select a project” on the Google Cloud Platform tab:
3. Then, click on the “ New Project” in the below screen:
4. Enter your Android project name and click on the “ Create” button. I will name the project as “GoogleTranslate”:
5. Your project will be displayed on the Google Cloud Platform dashboard. Select “ APIs and Services” on the navigation drawer at the left side:
6. Click on the “ Enable APIs and Services” button:
7. Type “ Cloud Translation API” in the search box and select the API:
8. You need to enable Cloud Translation API for your project by clicking on the “ Enable” button:
9. Click on the “ Enable Billing” in the screen below:
10. You will encounter the screen below. Click on the “ Create billing account” and continue:
11. Check “ I have read and agree to the Google Cloud Platform Free Trial Terms of Service.” and click on “ Agree and Continue”:
12. Enter your personal information:
13. After entering your Credit Card number, click on the “ Start my free trial”:
14. You are ready to manage Cloud Translation API for your project now. Click on “ Manage”:
15. Click on “ Create Credentials”:
16. Select “ Cloud Translation API”, check “ No, I’m not using them” and click on “ Which credentials do I need?” :
17. Enter your personal information, select “ JSON” as the key type and click on “ Continue”:
18. The credentials file of your project will be downloaded to your computer automatically in JSON format. Keep this file, for now, you will need the file soon 🙂
19. Now, you are ready to code! First, add internet permission to your AndroidManifest.xml file:
20. Add google cloud translate dependency to module level build.gradle. (It is the latest version of google cloud translate library for now, you can use the updated version if it is available in the future)
21. In order to prevent “ More the one file was found with OS independent path “project.properties” gradle error, add below code to the app level build.gradle:
22. Create a layout and add an EditText, a Button and a TextView. Therefore, when a text is entered to EditText and then Translate Button is clicked, the translated text will be displayed on a TextView.
23. We are almost done! Copy your credentials file in JSON format which you had downloaded at step 18 to raw resource directory. In order to create a raw resource directory:
Right click on res folder → Click on “ New” → Click on “ Android Resource Directory” and select Resource type as “ raw” from the list.
Then, move your credentials file in JSON format to the raw folder. It is important to note that the name of the files in the resource folders such as raw folder cannot contain uppercase characters, etc., so you need to consider the warning of Android Studio while naming your credentials file*:
“ File-based resource names must contain only lowercase a-z, 0–9, or underscore” characters”
*For simplicity, I just named the credentials file as “ credentials.json”.
24. Add the string of no internet connection warning to the strings.xml:
25. …and the last part is MainActivity.java:
First, translate service is gotten by getTranslateService() method. In this method, basically, the credentials which had been obtained from the Google API Console previously is set and translate service is connected.
After getting service by setting credentials, the translation process is carried out in the translate() method.
Also, we are checking the internet connection with the checkInternetConnection() method. Therefore, if there is no internet connection, “no connection” warning is displayed to the user at the TextView. If there is no problem related to the internet connection, translation is carried out and translated text is displayed at the TextView.
26. If you want to write your code in Kotlin, MainActivity.kt will be like below:
27. Cloud Translation API automatically detects the language which is translated to a target language. Therefore, you do not need to define the source language, but you have to define the target language.
I chose the target language as Turkish, so I used “ tr” abbreviation for my target language. Please find the abbreviation of your target language from the below link which includes supported languages:
Источник
Использование API Google Translate в Android
Я искал везде в Интернете для использования API Google Translate, но мне не удалось найти учебник по спускам или объяснение. Итак, вот что я сделал:
В моей консоли Google API я сгенерировал ключ в открытом доступе API с помощью моего SHA1 Fingerprint, используя этот ответ. Вот как выглядит консоль API:
В студии Android я создаю и отправляю свой запрос с помощью библиотеки OkHttp с помощью этого кода:
Он работает нормально, но в ответ я получаю:
В чем проблема? Правильно ли настроен API? Правильно ли я делаю звонок (я видел несколько библиотек, но с гидом)? Является ли этот разумный способ использования этой библиотеки? Что это значит?
Я думаю, что есть бесплатные демо-звонки бесплатно, и это не проблема.
Проблема в том, что при настройке ограничения API-ключа для приложения Android вы указали имя пакета и отпечаток сертификата SHA-1. Поэтому ваш ключ API будет принимать запрос от вашего приложения с именем пакета и указанным отпечатком сертификата сертификата SHA-1.
Итак, как Google знает, что запрос отправлен из вашего приложения ANDROID APP? Вы ДОЛЖНЫ добавить имя пакета приложения и SHA-1 в заголовке каждого запроса со следующими ключами:
Ключ: «X-Android-Package» , значение: название вашего приложения
Ключ: «X-Android-Cert» , значение: сертификат SHA-1 вашего apk
FIRST, получите подпись своего приложения SHA (вам понадобится библиотека Guava ):
Затем добавьте имя пакета и подпись сертификата SHA для запроса заголовка:
Источник
Android-er
For Android development, from beginner to beginner.
Thursday, October 8, 2009
AndroidTranslate, using Google Translate API in Android application.
Updated@2017-06-16:
Google’s CLOUD TRANSLATION API now is a paid API based on usage, refer https://cloud.google.com/translate/.
It’s a simple Android Application using google-api-translate-java to involve Google Translate, to translate the text input in the TextView in English to French.
In order to use google-api-translate-java in our application, we have to do some preparation as described in the article google-api-translate-java.
In our project, we have to grand permission to access internet, add the code in AndroidMainfest.xml.
Modify main.xml to include a EditText to input text to be translate, a Button to start translation, and a TextView to display the result.
main.xml can be downloaded here .
Finally, modify AndroidTranslate.java to implement the function.
AndroidTranslate.java can be downloaded here .
20 comments:
Thanks for help by provide such api.
sorry, but i am having two problems on Android Emulator:
(1)My Emulator not showing Hindi.
I choose English to Hindi.
but my emulator shows rectangle symbol.
(2)when I choose English to Gujarati
output text shows error.
so what should i do.provide solution step by step for above two problems.
Hello Patel Durgesh,
May be because emulator doesn’t support Hindi/Gujarati, I cannot select it by Menu > Settings > Language and Keyboard > Select Language.
As I know, «shows rectangle symbol» means the character cannot be displayed.
I’m a beginner into Android application i realy admired this application which i tried to run but i face one problem : that i get «Error» in the translated texte field .i’m sorry, i don’t speak english well .
i neeed your help friends.
thank you .
I don’t know your case exactly. Please note that Google Translate API is a online service, so you can take caution on:
— Grant permission to access internet.
— Make sure the 3G icon of the Android Emulator is on.
— Do you pass a proxy server? some proxy server disable connection to some site.
i don’t speak english well too:)
try <
Translate.setHttpReferrer(«http://android-er.blogspot.com/»);
OutputString = Translate.execute(InputString,fromLanguage, toLanguage);
> catch (Exception ex) <
ex.printStackTrace();
OutputString = «Error»;
>
this Error:- Cannot make a static reference to the non-static method execute(String, Language, Language) from the type Translate
this error occure in my code so please tell me about solve this problem.
Hey dear dillip i got solved the above two problems solved. 1-GoogleApi.setHttpReferrer
2-Translate.DEFAULT.execute
but still could not run the app
,still showing error. can anyone help..
Thanks in advance
How to fix error:
The method setHttpReferrer(String) is undefined for the type Translate
hello. can u please help me out. im a beginner..im stuck with some errors. firstly
the setcontentview() error..showing main cannot be resolved to a variable.
and Secondly..Translate isnt declared as a class..i dont know how to get over it..so please reply fast!!
import com.google.api.translate.Translate;
have an error even i imported jar file.how to reduce the error here
its not working. please check errors i need the code urgent.
it giving me error in this line
OutputString = Translate.execute(InputString, Language.ENGLISH, Language.HINDI);
like «Cannot make a static reference to the non-static method execute(String, Language, Language) from the type Translate»
i am new in android translate google api so i am using your code for translate English to hindi but so error at text place so plz help me
and error is it giving me error in this line
OutputString = Translate.execute(InputString, Language.ENGLISH, Language.HINDI);
like «Cannot make a static reference to the non-static method execute(String, Language, Language) from the type Translate»
This project is not working it’s give a error message.
Getting error in sethhtpreferrer showing cannot find symbol for this method please help me out
Hi
it is paid API .
@Hovsep Shakaryan yes it is paid we have to pay certain amount as per characters
where to insert google translate API key ?
ry <
Translate.setHttpReferrer(«http://android-er.blogspot.com/»);
OutputString = Translate.execute(InputString,fromLanguage, toLanguage);
> catch (Exception ex) <
ex.printStackTrace();
OutputString = «Error»;
>
output error. not working
Hi,
According to your latest update
(Updated@2017-06-16. ), Does that mean that the existing example will not work anymore?
Источник