AsyncTask的get()方法无法正常工作无法正常、方法、工作、AsyncTask

2023-09-08 10:19:16 作者:你的路过我的错过/*

我使用下面的code:

I am using the following code:

//(...)
translationTextView.setText("Searching for translation...");
translationTextView.setVisibility(View.VISIBLE);

myAsyncTask = (MyAsyncTask) new MyAsyncTask().execute(someString);

try {
    //As I understand it should wait here until AsyncTask is completed. But why for the time of execution translateTextView value is ""?
    translationTextView.setText(translateTask.get() + "<BR>");
} catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (ExecutionException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

问题是, translationTextView 值是,直到 myAsyncTask 结束。所以它看起来像

The problem is that translationTextView value is "" until myAsyncTask is finished. So it looks like

translationTextView.setText("Searching for translation...");

不叫。我做了什么错?

is not called. What did I do wrong?

推荐答案

这就是所谓的,但然后调用

It is called but then you call

translationTextView.setText(translateTask.get() + "<BR>");

的get()是一个阻塞调用

尝试,而不是在设置文本的 onPostExecute()。如果我理解正确的话那么这样的事情,你想要的东西应该给你

Try instead to set the text in your onPostExecute(). If I understand you correctly then something like this should give you what you want

   //(...)
        translationTextView.setText("Searching for translation...");
        translationTextView.setVisibility(View.VISIBLE);

        myAsyncTask = (MyAsyncTask) new MyAsyncTask().execute(someString);

然后,假设 MyAsyncTask 是一个内部类的活动的呼叫 translationTextView.setText ()插入无论你正试图从返回doInBackground()

Then, assuming MyAsyncTask is an inner class of your Activity call translationTextView.setText() inserting whatever you are trying to return from doInBackground()