我正在进行将一种语言翻译成另一种语言(英语)的活动。除我必须多次单击按钮才能工作外,其他所有功能都正常

在我的活动中,我想在单击imageView并将其转换为文本并在文本字段中显示时进行语音输入,然后按按钮将其转换为法语(当前为固定)并在textfield2中显示。 我正在使用yandex转换器。

我的错误:: 当我第一次单击按钮时,textfield2中什么也没有发生,但在日志中却显示正确的翻译。第二次单击后,它将更改textfield2。但是我只想在第一次单击后显示翻译。为什么在第二次单击后我的输出正确的情况下需要2次单击才能工作?

这是我的XML文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button"
        android:layout_centerHorizontal="true"
        android:layout_below="@+id/textView"
        tools:layout_editor_absoluteX="131dp"
        tools:layout_editor_absoluteY="202dp" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_centerHorizontal="true"
        android:layout_width="267dp"
        android:layout_height="244dp"
        app:srcCompat="@android:drawable/ic_btn_speak_now" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="30sp"
        android:layout_below="@+id/imageView"
        android:layout_centerHorizontal="true"
        android:text="Text to be Translated" />


    <TextView
        android:id="@+id/textView2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/button"
        android:text="Translated Text"
        android:textSize="30sp"
        />

</RelativeLayout>

这是我的MainActivity:

package com.example.translator;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;

import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;

public class MainActivity extends AppCompatActivity {

    final static int REQUEST_CODE_SPEECH=1000;
    ImageView listen;
    TextView ans,mresult;
    Context context=this;
    Button b;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        listen=findViewById(R.id.imageView);
        ans=findViewById(R.id.textView);
        mresult=findViewById(R.id.textView2);
        b=findViewById(R.id.button);
        listen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                speak();
            }
        });
        b.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String textToBeTranslated = ans.getText().toString();

                String languagePair = "en-fr"; //English to French ("<source_language>-<target_language>")
                //Executing the translation function
                Translate(textToBeTranslated,languagePair);
            }
        });
    }

    void Translate(String textToBeTranslated,String languagePair){
        TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);

        if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.HONEYCOMB) {
            translatorBackgroundTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,textToBeTranslated,languagePair);
        } else {
            translatorBackgroundTask.execute(textToBeTranslated,languagePair);
        }
        Log.d("Translation Result:", translatorBackgroundTask.t); // Logs the result in Android Monitor
        mresult.setText(TranslatorBackgroundTask.t);
    }
    void speak(){
        Intent intent=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
        intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
        intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "hi say something!!!");
        try{
            startActivityForResult(intent,REQUEST_CODE_SPEECH);
        }
        catch(Exception e) {
            Toast.makeText(MainActivity.this, "" + e.getMessage(),Toast.LENGTH_LONG).show();
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
    switch(requestCode){
        case REQUEST_CODE_SPEECH:{
          if(resultCode==RESULT_OK && data!=null) {
              ArrayList<String>result=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
              ans.setText(result.get(0));
          }
          break;
        }
    }
    }
}

这是我的API文件:

package com.example.translator;

import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

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

    @Override
    public 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 = "MY-API-KEY";
            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
            bufferedReader.close();
            inputStream.close();
            httpJsonConnection.disconnect();

            //Making result human readable
            String 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);
            t=resultString;
            return jsonStringBuilder.toString().trim();

        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

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

    }

    @Override
    protected void onPostExecute(String result) {
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }
}
评论
  • 过路人
    过路人 回复

    我认为这是这行:

    mresult.setText(TranslatorBackgroundTask.t);
    

    不应该是:

    mresult.setText(translatorBackgroundTask.t);