gpt4 book ai didi

java - 我正在开展将一种语言翻译成另一种语言(英语-法语)的 Activity 。一切正常,除了我必须多次单击按钮才能工作

转载 作者:行者123 更新时间:2023-12-01 17:13:44 25 4
gpt4 key购买 nike

在我的 Activity 中,我想在单击 imageView 时进行语音输入并转换为文本并将其显示在文本字段中,按下按钮后将其转换为法语(目前已修复)并将其显示在文本字段2中。我正在使用 yandex 翻译器。

我的错误::当我第一次单击按钮时,textfield2 中没有任何反应,但在日志中,它显示正确的翻译。第二次单击后,它更改了 textfield2。但我只想在第一次点击后显示翻译。为什么需要点击两次才能工作,而我的输出在第二次点击后就正确了?

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

这是我的主要 Activity :

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

关于java - 我正在开展将一种语言翻译成另一种语言(英语-法语)的 Activity 。一切正常,除了我必须多次单击按钮才能工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61409056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com