当我调试我的应用程序时,我看到onPostExecute在onPreExecute后启动,并且只有在完成时doInBackground方法才开始运行,所以我没有UI上的结果。为什么会这样?的AsyncTask代码:为什么onPostExecute可以在AsyncTask的doInBackground之前运行?
class TranslateYandex extends AsyncTask<Void, Void, Void> {
String translate = "";
// YandexTranslation yandexTranslation;
@Override
protected void onPreExecute() {
super.onPreExecute();
enterWord.setEnabled(false);
getTranslateButton.setEnabled(false);
translate = enterWord.getText().toString();
}
@Override
protected Void doInBackground(Void... voids) {
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://translate.yandex.net")
.addConverterFactory(GsonConverterFactory.create())
.build();
YandexService service = retrofit.create(YandexService.class);
Call<YandexTranslation> call = service.getTranslation(translate, API_KEY, LANG);
call.enqueue(new Callback<YandexTranslation>() {
@Override
public void onResponse(Call<YandexTranslation> call, Response<YandexTranslation> response) {
if (response.body() != null){
Log.i("Response", response.body().getTranslation().get(0));
translation = response.body().getTranslation().get(0);
int donothing = 1;
}
else {
Log.i("Response", " is null");
}
}
@Override
public void onFailure(Call<YandexTranslation> call, Throwable t) {
Log.i("Failure", t.toString());
}
});
return null;
}
protected void onPostExecute(Void voids) {
enterWord.setEnabled(true);
getTranslateButton.setEnabled(true);
enterTranslation.setText(translation);
}
}
因为你在'doInBackground()'中做的事情本身就是异步的。也就是说,你不需要把它们放在'AsyncTask'中。 –
您没有在'onPostExecute'上放置'@ Override'注释 –
@KevinMurvie Java中不需要'@ Override'注解。签名对于给定的类型参数是正确的。 –