AsyncTask和子类化

时间:2013-05-28 03:48:18

标签: android android-asynctask

我在继承AsyncTask时遇到以下问题:

-compile:
    [javac] Compiling 6 source files to C:\DEV\MyProject\bin\classes
    [javac] C:\DEV\MyProject\src\org\example\myproject\MainActivity.java:234: error:
method does not override or implement a method from a supertype
    [javac]     @Override
    [javac]     ^
    [javac] C:\DEV\MyProject\src\org\example\myproject\MainActivity.java:286: error:
method does not override or implement a method from a supertype
    [javac]     @Override
    [javac]     ^
    [javac] 2 errors

我的代码(doInBackground也在这里编译器没有抱怨):


protected class DoThingsTask extends AsyncTask
    @Override
    protected Void doInBackground(String... params)
    {
        // things
    }

    @Override
    protected void onPreExecute(Void... params)
    {
        super.onPreExecute();
        // ... do things
        Log.i(TAG, "AsyncTask: pre-execution done");
    }

    @Override
    protected void onPostExecute(Void... result)
    {
        Log.i(TAG, "AsyncTask: PostExecution start");
        // .... do other things
        Log.d(TAG, "AsyncTask PostExecution done");
    }

因此编译器抱怨@Override注释。如果我删除了注释,它编译得很好但不会调用onPreExecuteonPostExecute。我不知道为什么会有这个问题。

我在这里使用命令行 - 所以我每次都在调用ant clean

赞赏的想法!

3 个答案:

答案 0 :(得分:3)

你的参数错了。 OnPreExecute不带参数。 onPostExecute采用Result类型的单个参数(其中result是您选择的任何一种类型)。它不需要可变参数。

答案 1 :(得分:1)

我的猜测是你的AsyncTask类指定了不同的参数类型,例如:

private class Example extends AsyncTask<String, Void, String> {
     @Override 
     protected String doInBackground(String... params) {
       //this is correct @Override, the doInBackground has the same variable type of String
     }

     @Override
     protected void onPostExecute(Void... params) {
       //this is Wrong @Override, the Post result should be String
       //as shown by <String, Void, String>
       //the correct one should be :
       //@Override
       //protected String onPostExecute (String...params) {
       //.....
       //.....}
     }
}

同样,正如Gabe Sechan指出的那样,onPreExecute不接受任何参数,因此无法覆盖它,尝试将其修改为:

@Override
protected void onPreExecute()
{
    super.onPreExecute();
    // ... do things
    Log.i(TAG, "AsyncTask: pre-execution done");
}

编辑,您错误地声明了asyncTask,您应该指定asnyctask的参数,如下所示:

private class Example extends AsyncTask<InputType, ProgressType, ResultType>

如果您想使其无效,请使用Void作为参数类型。

祝你好运^^

答案 2 :(得分:0)

您从AsyncTask派生的类应该在其下面有红色的squigly行以获取错误。如果按...

视窗: Ctrl + 1

的Mac: Command + 1

快速修复(或者只是将鼠标悬停在红色边缘)

它应该说“添加未实现的方法”并为您做繁重的工作。如果onPreExecute和onPostExecute没有实现,请右键单击该类并点击source - &gt;覆盖/实现方法并找到您要查找的方法。 `