How to translate text from one language to another language android?

Shark picture Shark · Oct 31, 2014 · Viewed 22.4k times · Source

I have a response which I parse from json and displayed the result. Is it possible to convert to other language like French, Hindi, German?

When I browsed, I came to know google stopped on 2011 as free version and started pricing. Is there any free version to convert the response text to other language?

Piece of code is as follows:

  TextView text; // created an id.

  JSONObject jsono=new JSONObject(data);
  JSONArray jarray = jsono.getJSONArray("posts");
  for (int i = 0; i < jarray.length(); i++) {
   JSONObject object = jarray.getJSONObject(i);
  String name= object.getString("name");
  text.setText(name);// how to convert this to other language. 

Say for eg: response what I get is Good morning. which I need to translate and display in textview as Bonjour which is in French.

Answer

bachr picture bachr · Oct 31, 2014

Here is a detailed blog post on using different translation services on an Android app. The source code is on github with a sample of using MyMemory service for translation.

/** Translate a given text between a source and a destination language */
public String translate(String text) {      
    String translated = null;
    try {
        String query = URLEncoder.encode(text, "UTF-8");
        String langpair = URLEncoder.encode(srcLanguage.getLanguage()+"|"+dstLanguage.getLanguage(), "UTF-8");
        String url = "http://mymemory.translated.net/api/get?q="+query+"&langpair="+langpair;
        HttpClient hc = new DefaultHttpClient();                 
        HttpGet hg = new HttpGet(url);
        HttpResponse hr = hc.execute(hg);
        if(hr.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {                
            JSONObject response = new JSONObject(EntityUtils.toString(hr.getEntity()));
            translated = response.getJSONObject("responseData").getString("translatedText");                
        }
    } catch (Exception e) {
        e.printStackTrace();
    }       
    return translated;      
}