【问题标题】:AsyncTask not even startingAsyncTask 甚至没有启动
【发布时间】:2014-09-30 19:58:01
【问题描述】:

我在 AyncTask 的一个代码上坐了 5 个小时,但运行不正常。我刚刚创建了另一个简单的Activity(因为在最后一个onPostExecute() 没有工作)现在这个简单的Activity 也没有启动AsyncTask。谁能看到我做错了什么?

public class ServerStatus extends Activity {
Context context;    
private ProgressDialog pd;  
int a;  
TextView test;  
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.server_status);
        context=this;
        test=(TextView) findViewById(R.id.welcomemessage);
        new Download().execute();


    }

    public class Download extends AsyncTask<Void, Void, Void>{

        protected Void onPreExecute(Void... arg0) {
            pd = new ProgressDialog(context);
            pd.setTitle("Processing...");
            pd.setMessage("Please wait.");
            pd.setCancelable(false);
            pd.setIndeterminate(true);
            pd.show();
            return null;
        }


        @Override
        protected Void doInBackground(Void... arg0) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            a++;
            return null;
        }


        protected Void onPostExecute(Void... arg0) {
            if (pd!=null) 
                pd.dismiss();
            test.setText(a);
            return null;
        }

    } 

}

另外,NavigationDrawer 会阻塞 UI 线程吗?因为当我实现它时,我什至无法更新TextView

【问题讨论】:

  • 您应该在 onProgressUpdate() 中进行 UI 组件修改。导航抽屉不会阻塞 UI 线程。当您尝试运行它时会发生什么?
  • 这是我的[对类似问题的回答][1] [1]:stackoverflow.com/questions/25752210/…
  • 嗯,我正在从 onPostExecute() 更新 UI 线程,所以可能是我的问题(它没有更新任何东西,甚至没有做任何没有被调用的事情)。那明天试试感谢您的建议。
  • 你真的应该使用@Override 注释。您的编译器会立即告诉您问题。

标签: android android-asynctask navigation-drawer progressdialog


【解决方案1】:

方法不正确。你应该给它们添加@Override注解,这样当你做错的时候它就会对你大喊大叫。

onPreExecute() 不需要任何params 所以应该是

@Override
protected Void onPreExecute() {

还将 `onPostExecute() 的参数类型更改为

@Override
 protected Void onPostExecute(Void arg0) {

删除“...”See Varargs 以获得解释。

Docs

Post explaining AsyncTask and getting values

类声明中的那些参数用于doInBackground()onProgressUpdate()onPostExecute()

至于NavDrawer,我不确定你遇到了什么问题。

【讨论】:

  • 似乎正在工作,但可能我做错了什么,因为在将@Override 添加到 onPostExecute() 之后,它说“ServerStatus.download 类型的 onPostExecute(Void...) 方法必须覆盖或实现超类型方法”。可能我在争论中搞砸了,但如果您或其他人能纠正我,我将不胜感激。 5 小时后,我没有直接思考......
【解决方案2】:

您需要更改 onPreExecute 中的代码

pd = new ProgressDialog(context);

pd = new ProgressDialog(getActivity());

【讨论】:

  • ServerStatus.download 类型的方法 getActivity() 未定义
  • 对不起,我以为你在处理 Fragments,我的错
猜你喜欢
  • 2017-09-25
  • 2023-04-01
  • 1970-01-01
  • 2018-03-17
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多