Android Translation application using yandex api showing result in emulator text view but not in real device

1.2k views Asked by At

I am trying to make a translation application from English to Bangla using Yandex API.

It works fine in the emulator but in the real device it shows result for only one word in the text view but when writing a sentence it shows null / nothing.

I think the problem is buffer overflow but don't know how to fix it for the real device. Here are some reference pictures. In the emulator the result works fine:

In the emulator the result works fine

In the real device it shows empty in text view:

In the real device it shows empty in text view

But it works fine when a single word is used in real device.

Here is the code for my Asynctask:

public class

    TranslatorBackgroundTask extends AsyncTask<String, Void, String> {
    //Declare Context
    Context ctx;
    //Set Context
    TranslatorBackgroundTask(Context ctx){
        this.ctx = ctx;
    }

    String resultString;

    @Override
    protected String doInBackground(String... params) {
        //String variables
        String textToBeTranslated = params[0];
        String languagePair = params[1];

        String jsonString;

        try {
            //Set up the translation call URL
            String yandexKey = "trnsl.1.1.20170823T130435Z.79a583874abfc8ff.61e23593359fdc92452e69a3d5ec05347fc4180b";
            String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
                    + "&text=" + textToBeTranslated + "&lang=" + languagePair;
            URL yandexTranslateURL = new URL(yandexUrl);

            //Set Http Conncection, Input Stream, and Buffered Reader
            HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
            InputStream inputStream = httpJsonConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));

            //Set string builder and insert retrieved JSON result into it
            StringBuilder jsonStringBuilder = new StringBuilder();
            while ((jsonString = bufferedReader.readLine()) != null) {
                jsonStringBuilder.append(jsonString + "\n");
            }

            //Close and disconnect
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            inputStream.close();
            httpJsonConnection.disconnect();

            //Making result human readable
            resultString = jsonStringBuilder.toString().trim();

            //Getting the characters between [ and ]

            resultString = resultString.substring(resultString.indexOf('[')+1);
            resultString = resultString.substring(0,resultString.indexOf("]"));

            //Getting the characters between " and "
            resultString = resultString.substring(resultString.indexOf("\"")+1);
            resultString = resultString.substring(0,resultString.indexOf("\""));

            Log.d("Translation Result:", resultString);
            return jsonStringBuilder.toString().trim();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
    //String text = String.valueOf(resultString);

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected void onPostExecute(String result) {
        MainActivity.tvTranslatedText.setText(resultString);
        Toast.makeText(ctx, resultString, Toast.LENGTH_LONG).show();
        super.onPostExecute(result);
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}

And the code for the main activity:

public class MainActivity extends AppCompatActivity{

    Context context=this;
    private static final int REQUEST_CODE = 1234;
    static TextView tvTranslatedText;
    EditText etUserText;
    Button buTranslate;
    Button buSpeak;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.layout_activity_main);
            tvTranslatedText = (TextView)findViewById(R.id.tvTranslatedText);
            etUserText = (EditText)findViewById(R.id.etUserText);

            buTranslate = (Button)findViewById(R.id.buTranslate);

            buSpeak = (Button)findViewById(R.id.buSpeak);
        }



    public void buTranslate(View view) {
        //Default variables for translation
        String textToBeTranslated = "";
        textToBeTranslated= etUserText.getText().toString();
        String languagePair = "en-bn"; //English to bengali ("<source_language>-<target_language>")
        //Executing the translation function
        Translate(textToBeTranslated,languagePair);

    }


    //Function for calling executing the Translator Background Task
    void Translate(String textToBeTranslated, String languagePair){
        TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);

        String translationResult = "";

        translationResult = String.valueOf(translatorBackgroundTask.execute(textToBeTranslated,languagePair)); // Returns the translated text as a String
        Log.d("Translation Result",translationResult); // Logs the result in Android Monitor

    }

    //Speak button activities

    public void buSpeak(View view) {
        startVoiceRecognitionActivity();
    }

    private void startVoiceRecognitionActivity()
    {
        Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
                RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Speak to translate");
        startActivityForResult(intent, REQUEST_CODE);
    }

    /**
     * Handle the results from the voice recognition activity.
     */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {

            if (data != null) {

                //pull all of the matches
                ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                String topResult = matches.get(0);

                EditText AutoText = (EditText) findViewById(R.id.etUserText);
                AutoText.setText(topResult);
            }
        }
    }
}

The error message:

Caused by: com.google.android.apps.gsa.shared.exception.GsaIOException: Error code: 393238 | Buffer overflow, no available space.

1

There are 1 answers

3
touhid udoy On

Why didn't you add a listener to your sample code?

Try adding these on onCreate in MainActivity:

buTranslate.setOnClickListener(
    new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            buTranslate(view);
        }
    }
);

Update: There was another issue. Emulators on android sdk 16 don't show Unicode properly. Thats why you don't see your results, as those are Unicodes. Try Log to print your resultString.