3

我正在尝试使用 Yandex API 制作从英语到孟加拉语的翻译应用程序。

它在模拟器中运行良好,但在真实设备中,它仅在文本视图中显示一个单词的结果,但在编写句子时它显示空/无。

我认为问题是缓冲区溢出,但不知道如何为真实设备修复它。这里有一些参考图片。在模拟器中,结果工作正常:

在模拟器中,结果工作正常

在真实设备中,它在文本视图中显示为空:

在真实设备中,它在文本视图中显示为空

但在真实设备中使用单个单词时效果很好。

这是我的 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);
    }
}

主要活动的代码:

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);
            }
        }
    }
}

错误信息:

引起:com.google.android.apps.gsa.shared.exception.GsaIOException:错误代码:393238 | 缓冲区溢出,没有可用空间。

4

1 回答 1

0

你为什么不给你的示例代码添加一个监听器?

尝试将这些添加onCreateMainActivity

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

更新: 还有另一个问题。android sdk 16 上的模拟器无法正确显示 Unicode。这就是为什么您看不到结果的原因,因为这些是 Unicode。尝试Log打印您的resultString.

于 2017-12-12T17:20:27.630 回答