Android异步任务编译器错误

时间:2014-11-20 21:04:20

标签: android android-asynctask

我的异步方法给出了编译器错误。这是我的代码:

private void registerInBackground() {
    new AsyncTask() {
        @Override
        protected String doInBackground(Void... params) {

        }

        @Override
        protected void onPostExecute(String msg) {

        }
    }.execute(null, null, null);
}

对于第2行,我收到此错误:

Multiple markers at this line
    - The type new AsyncTask(){} must implement the inherited abstract method AsyncTask.doInBackground(Object...)
    - Type safety: The method execute(Object...) belongs to the raw type AsyncTask. References to generic type AsyncTask<Params,Progress,Result> should be 
     parameterized
    - AsyncTask is a raw type. References to generic type AsyncTask<Params,Progress,Result> should be parameterized

对于第4行,我收到此错误:

The method doInBackground(Void...) of type new AsyncTask(){} must override or implement a supertype method

我该如何解决?我的代码出了什么问题?

2 个答案:

答案 0 :(得分:0)

AsyncTask构造函数中添加泛型类类型:

private void registerDoInBackground() {
    new AsyncTask<Void, Void, String>() {
        @Override
        protected String doInBackground(Void... params) {

        }

        @Override
        protected void onPostExecute(String msg) {

        }
    }.execute(null, null, null);
}

答案 1 :(得分:0)

AsyncTask是一个参数化类,因为您没有指定参数,编译器假定您打算使用Object类型作为参数。您正在使用Void ...作为doInBackground的参数,在这种情况下您应该使用Object []或Object ....

@Override
protected Object doInBackground(Object[] objects) {
    return null;
}