-1
嗨我所有新來的Android和我正在建立一個英語到德語翻譯器的應用程序,我得到上述錯誤的代碼行: 可以請幫助我如何解決這個問題。Android錯誤:必須從UI線程調用方法gettext當前推斷的線程正在工作
package com.exmaple.android.lang_trans;
import java.util.Locale;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.exmaple.android.lang_trans.R;
import com.memetix.mst.language.Language;
import com.memetix.mst.translate.Translate;
public class MainActivity extends Activity implements OnInitListener {
private TextToSpeech tts;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tts = new TextToSpeech(this, this);
((Button) findViewById(R.id.bSpeak)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
speakOut(((TextView) findViewById(R.id.tvTranslatedText)).getText().toString());
}
});
((Button) findViewById(R.id.bTranslate)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
class bgStuff extends AsyncTask<Void, Void, Void> {
String translatedText = "";
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
//below line is throwing the error
String text = ((EditText) findViewById(R.id.etUserText)).getText().toString();
translatedText = translate(text);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
translatedText = e.toString();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
((TextView) findViewById(R.id.tvTranslatedText)).setText(translatedText);
super.onPostExecute(result);
}
}
new bgStuff().execute();
}
});
}
public String translate(String text) throws Exception {
// Set the Client ID/Client Secret once per JVM. It is set statically and applies to all services
Translate.setClientId("CLIENT ID"); //Change this
Translate.setClientSecret("CLIENT SECRET"); //change
String translatedText = "";
translatedText = Translate.execute(text, Language.GERMAN);
return translatedText;
}
@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.GERMAN);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
//speakOut("Ich");
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speakOut(String text) {
tts.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
嗨@Aravinda如果此答案已解決您的問題,請考慮通過點擊複選標記來接受它。這向更廣泛的社區表明,您已經找到了解決方案,併爲答覆者和您自己提供了一些聲譽。沒有義務這樣做。 –