1

I am creating a translator app where I am getting the input text from android supported voice Recognizer. Example : Hindi, Chinese, etc. Now I want to build the query like this -

public JSONObject getTranslatedText() {
    StringBuilder sb = new StringBuilder();
    String http = "https://translation.googleapis.com/language/translate/v2?key=xyz";
    JSONObject response = null;
    String json = "";

    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(http);
        urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setUseCaches(false);
        urlConnection.setRequestMethod("POST");
        urlConnection.setRequestProperty("Content-Type", "application/json");

        urlConnection.connect();

        String line1 = "{\n" + "  'q': '" + inputString + "',\n" + "  'target': '" + targetcodeString + "'\n" + "}";

        DataOutputStream out = new DataOutputStream(urlConnection.getOutputStream());
        out.writeBytes(line1);
        out.flush();
        out.close();

        BufferedReader br = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));
        String line = null;
        while ((line = br.readLine()) != null) {
            sb.append(line + "\n");
        }
        br.close();
        json = sb.toString();
        response = new JSONObject(json);
    } catch (MalformedURLException e) {

    } catch (IOException e) {

    } catch (JSONException e) {

    } finally {
        if (urlConnection != null) urlConnection.disconnect();

    }
    return response;
}

The problem is it is not encoding properly and I am getting output like this - Example: For a word "How are you" in Hindi i.e "क्या हाल" as 9 & HG 08 * E

Can I get some help please. Thanks in advance.

MPhil
  • 881
  • 1
  • 12
  • 24
Anupam
  • 2,845
  • 2
  • 16
  • 30
  • try setting unicode characters using `yourTextView.setText(Html.fromHtml("your chars"));` – ELITE Jul 28 '17 at 10:24
  • It doesn's work. tried it. – Anupam Jul 28 '17 at 10:39
  • check [display-different-languages-in-set-in-textview](https://stackoverflow.com/questions/15462171/display-different-languages-in-set-in-textview) and [urdu-font-in-textview](https://stackoverflow.com/questions/15492398/urdu-font-in-textview) – ELITE Jul 28 '17 at 10:46
  • I am not setting the text to a textview. If I set also it works fine. The question is while Encoding the string in Buffered Reader for other languages is not working. It is only taking English with UTF-8. Is there any suggestion? – Anupam Jul 28 '17 at 10:52
  • what if `new InputStreamReader(urlConnection.getInputStream());` removed `"UTF-8"` – ELITE Jul 28 '17 at 11:12
  • Still not working. – Anupam Jul 28 '17 at 11:34

1 Answers1

0

Try using Html.fromHtml(yourTranslatedStr).toString(). I tried that with Hindi and it worked.

Distra
  • 2,260
  • 2
  • 14
  • 23