AsyncTask get()方法无法正常工作
我使用以下代码:
//(...) 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() + "
"); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); }
问题是translationTextView
值是“”,直到myAsyncTask
完成。 所以它看起来像
translationTextView.setText("Searching for translation...");
不叫。 我做错了什么?
它被调用但是你打电话
translationTextView.setText(translateTask.get() + "
");
和get()
是一个阻塞调用
请尝试在onPostExecute()
设置文本。 如果我理解正确,那么这样的事情应该能给你你想要的东西
//(...) translationTextView.setText("Searching for translation..."); translationTextView.setVisibility(View.VISIBLE); myAsyncTask = (MyAsyncTask) new MyAsyncTask().execute(someString);
然后,假设MyAsyncTask
是您的Activity
调用translationTextView.setText()
的内部类,插入您尝试从doInBackground()
返回的任何内容
正如codeMagic指出的那样,如果你还没有覆盖AsyncTask
子类的onPostExecute()
方法。 它在主线程上执行,你应该在那里更新你的UI。