Kalex Kalex -5 years ago 145
Android Question

How to use Microsoft Translation API for android?

Ok, my question is how to use Microsoft translation API for android? My problem is that I am creating an android app that will take input from one EditText, and when a button called Translate is pressed it will translate that text into another language, the translated text is then set to the another EditText... I have written some code, can you tell me what wrong with that code because its not working at all, it is not taking input and hence not producing output... thanks...

package kalex.globaltranslate;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;

import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;

public class TranslateActivity extends Activity implements OnClickListener {

public void onCreate(Bundle savedInstanceState) {
Translate.setClientId("MY ID");
Translate.setClientSecret("MY SECRET KEY");
Button Trans = (Button)findViewById(R.id.translate);

public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_translate, menu);
return true;

public void onClick(View v) {
//get the text entered
EditText Input = (EditText)findViewById(R.id.input);
EditText Output = (EditText)findViewById(R.id.output);

String In =Input.getText().toString();
//String Out;
try {
String Out = Translate.execute(In, Language.AUTO_DETECT, Language.FRENCH);

} catch (Exception e) {
// TODO Auto-generated catch block


Answer Source

Firstly, you may want to read a bit more about Java programming in general.

Your object instances should be named with small letters. For example EditText Input should be EditText input.

I recommend that you reorganize your program, by moving

EditText Input = (EditText)findViewById(R.id.input);
EditText Output = (EditText)findViewById(R.id.output);

in the beginning, after the "Trans" instantiation. Then make global variable of those objects, so you can access them in the OnClick event.

Your onClick method doesn't check the id of the view which is passed and you may shoot yourself in the foot like this. It's common to make a switch statement with cases for all views which have listeners. Alternatively - you can also have dedicated ClickListeners for all elements (less efficient, but still systematic):

private OnClickListener translateClick = new OnClickListener() {

            public void onClick(View v) {
                    // TODO

and set it to your translate button - trans.setOnClickListener(translateClick);

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download