當我調試我的應用程序時,我看到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'註解。簽名對於給定的類型參數是正確的。 –