How to use Microsoft Translation API in android

April 27, 2013 | Rishabh Agrawal | General

I am going to use the Bing Translate API – (unfortunately Google translate API isnt free).
First, download “java library”. Place this in your libs folder.

We need the Client Id and Client username from the Microsoft MarkerPlace. You can get this from: http://blogs.msdn.com/b/translation/p/gettingstarted1.aspx  .

You’ll get the complete code from here:

Add these permissions in your manifest file

   

<uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

 

 

This is your main activity class:

public class MainActivity extends Activity implements OnInitListener {



private TextToSpeech tts;

          Locale[] locales;

          String listLocales;

          String selectedLanguage;

          String[] langList = new String[9];



          Language languagelist;



          final int Arabic = 1, Hindi = 2, French = 3, Russian = 4, German = 5,

                             Chinese = 6, Japanese = 7, Italian = 8, Spanish = 9;



          ArrayList<String> listOfLanguage = new ArrayList<String>();



          public int postion;



          @Override

          public void onCreate(Bundle savedInstanceState) {

                   super.onCreate(savedInstanceState);

                   setContentView(R.layout.activity_main);

                   locales = Locale.getAvailableLocales();



                   String[] langListForDialogBox = { "Arabic", "Hindi", "French",

                                      "Russian", "German", "Chinese", "Japanes", "Italian", "Spanish" };



                   for (int i = 0; i < langListForDialogBox.length; i++) {

                             listOfLanguage.add(langListForDialogBox[i]);

                             langList[i] = langListForDialogBox[i];

                   }



                   tts = new TextToSpeech(this, this);

                   ((Button) findViewById(R.id.bSpeak))

                                       .setOnClickListener(new OnClickListener() {



                                                @Override

                                                public void onClick(View v) {

                                                          // TODO Auto-generated method stub

                                                          speakOut(((TextView) findViewById(R.id.tvTranslatedText))

                                                                             .getText().toString());

                                                }

                                      });



                   ((Button) findViewById(R.id.selectLangButton))

                                      .setOnClickListener(new OnClickListener() {



                                                @Override

                                                public void onClick(View v) {



                                                          AlertDialog.Builder singlechoicedialog = new AlertDialog.Builder(

                                                                             MainActivity.this);

                                                          singlechoicedialog.setSingleChoiceItems(langList, 0,

                                                                             new DialogInterface.OnClickListener() {

                                                                                      public void onClick(DialogInterface dialog, int item) {

postion = item;

 listOfLanguage.get(item);

                                                                                                                     switch (item) {

                                                                                                case 0:

                                                                                                languagelist = Language.ARABIC;

                                                                                                          break;

                                                                                                case 1:

                                                                                                          languagelist = Language.HINDI;

                                                                                                          break;

                                                                                                case 2:

                                                                                                         languagelist = Language.FRENCH;

                                                                                                          break;

                                                                                                case 3:

                                                                                                          languagelist = Language.RUSSIAN;

                                                                                                          break;

                                                                                                case 4:

                                                                                                          languagelist = Language.GERMAN;

                                                                                                          break;

                                                                                                case 5:

                                                                                                          languagelist = Language.CHINESE_SIMPLIFIED;

                                                                                                          break;

                                                                                                case 6:

                                                                                                          languagelist = Language.JAPANESE;

                                                                                                          break;

                                                                                                case 7:

                                                                                                          languagelist = Language.ITALIAN;

                                                                                                          break;

                                                                                                case 8:

                                                                                                          languagelist = Language.SPANISH;

                                                                                                          break;



                                                                                                default:

                                                                                                          languagelist = Language.FRENCH;

                                                                                                          break;

                                                                                                }



                                                                                                dialog.cancel();

                                                                                      }

                                                                             });

                                                          AlertDialog alert_dialog = singlechoicedialog.create();

                                                          alert_dialog.show();



                                                          // set defult select value

                                                          alert_dialog.getListView()

                                                                             .setItemChecked(postion, true);

                                                }

                                      });



                   ((Button) findViewById(R.id.bTranslate))

                                      .setOnClickListener(new OnClickListener() {



                                                @Override

                                                public void onClick(View v) {

                                                          // TODO Auto-generated method stub



                                                          class bgStuff extends AsyncTask<Void, Void, Void> {



                                                                   String translatedText = "";



                                                                   @Override

                                                                   protected Void doInBackground(Void... params) {

                                                                             // TODO Auto-generated method stub

                                                                             try {

                                                                                      String text = ((EditText) findViewById(R.id.etUserText))

                                                                                                          .getText().toString();

                                                                                      translatedText = translate(text,

                                                                                                          selectedLanguage);

                                                                             } catch (Exception e) {

                                                                                      // TODO Auto-generated catch block

                                                                                      e.printStackTrace();

                                                                                      translatedText = e.toString();

                                                                             }



                                                                             return null;

                                                                   }



                                                                   @Override

                                                                   protected void onPostExecute(Void result) {

                                                                             // TODO Auto-generated method stub

                                                                             ((TextView) findViewById(R.id.tvTranslatedText))

                                                                                                .setText(translatedText);

                                                                             super.onPostExecute(result);

                                                                   }



                                                          }



                                                          new bgStuff().execute();

                                                }

                                      });

          }



          public void displayListView() {

                   // TODO Auto-generated method stub



          }



          public String translate(String text, String selectedLanguage)

                             throws Exception {



                   Translate.setClientId("Nishanttyest"); // Change this

                   Translate

                                      .setClientSecret("OO5K4SEmwrrfR3P9pAmJCBEvl94kkwMCkJXeN3IwsG4=");



                   String translatedText = "";

                   // Language ll = selectedLanguage;



                   translatedText = Translate.execute(text, languagelist);



                   return translatedText;

          }



          @Override

          public void onInit(int status) {

                   if (status == TextToSpeech.SUCCESS) {



                             int result = tts.setLanguage(Locale.ENGLISH);



                             if (result == TextToSpeech.LANG_MISSING_DATA

                                                || result == TextToSpeech.LANG_NOT_SUPPORTED) {

                                      Log.e("TTS", "This Language is not supported");

                             } else {



                                      // speakOut("Ich");

                             }



                   } else {

                             Log.e("TTS", "Initilization Failed!");

                   }

          }



          private void speakOut(String text) {

                   tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);

          }



          // if button is clicked, close the custom dialog



}

Your XML file will be like this

<RelativeLayout 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" >

    <RelativeLayout

        android:layout_width="wrap_content"

        android:layout_height="wrap_content" >

        <TextView

            android:id="@+id/EnterString"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_alignBaseline="@+id/etUserText"

            android:layout_alignBottom="@+id/etUserText"

            android:layout_alignParentLeft="true"

            android:text="@string/text4TextView" />

        <EditText

            android:id="@+id/etUserText"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_toRightOf="@+id/EnterString"

            android:ems="10" />

        <Button

            android:id="@+id/selectLangButton"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_below="@+id/etUserText"

            android:layout_centerHorizontal="true"

            android:layout_marginTop="10dip"

            android:text="@string/text4desireBtn" />

        <Button

            android:id="@+id/bTranslate"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_below="@+id/selectLangButton"

            android:layout_centerHorizontal="true"

            android:text="@string/text4transBtn" />

        <TextView

            android:id="@+id/tvTranslatedText"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_centerHorizontal="true"

            android:layout_below="@+id/bTranslate"

            android:text="@string/text4TransTextView"

            android:textAppearance="?android:attr/textAppearanceLarge" />

        <Button

            android:id="@+id/bSpeak"

            android:layout_width="wrap_content"

            android:layout_height="wrap_content"

            android:layout_alignParentBottom="true"

            android:layout_centerHorizontal="true"

            android:text="@string/text4speakBtn" />

    </RelativeLayout>

</RelativeLayout>

 

 

?ui=2&ik=9bfd934bb5&view=att&th=13e4b72424f5fb1e&attid=0     ?ui=2&ik=9bfd934bb5&view=att&th=13e4b72424f5fb1e&attid=0      ?ui=2&ik=9bfd934bb5&view=att&th=13e4b72424f5fb1e&attid=0

 

Hope you all like my post and  find it useful if you are unable to understand any step please let me know in comment section..I’ll try to make it more explanatory!!

Post by Nishant Anindya


THE AUTHORRishabh Agrawal

Rishabh Agrawal is the founder of Creatiosoft, a company focused on creating high-quality software for the iGaming industry, specialising in poker and card games. With years of experience, Rishabh is dedicated to delivering engaging and user-friendly gaming experiences. Through this blog, he shares his passion and insights to help readers understand the latest trends and advancements in iGaming.

Recent Posts

The Future of Mobile Gaming: What to Expect in the Next 5 Years

Over the years, mobile gaming has seen amazing development and innovation utilized by the game development company in India. It…
06 Jun 2023 Rishabh Agrawal

How Do I Get Started With NFT Gaming?

The popularity of the NFT game has created a different fan base. There was a time when games were a…
18 Jul 2022 Rishabh Agrawal

What Are The Top Trends in NFT Marketplace 2022?

The NFTs are the new engaging and revolutionary technology across the globe. Though, these non-fungible tokens appeared for the first…
09 Jun 2022 Rishabh Agrawal