AsyncTask not generic?
When I try to compile to following code, I get two errors:
Description Resource Path Location Type Syntax error on token "void", invalid Expression AsyncTask.java /AsyncTask Project/src/org/me/asynctask line 19 Java Problem
Description Resource Path Location Type The type AsyncTask is not generic; it cannot be parameterized with arguments AsyncTask.java /AsyncTask Project/src/org/me/asynctask line 25 Java Problem
package org.me.asynctask;
import android.app.Activity; import android.content.Context; import android.os.Bundle; import android.widget.TextView; import android.widget.Toast; import android.os.*; public class AsyncTask extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main);
TextView mytextview = new TextView(this);
TextView secondtextview = new TextView(this);
new MyAsyncClass().execute(mytextview, void, secondtextview);
}
private class MyAsyncClass extends AsyncTask<TextView, Void, Void> {
protected TextView doInBackground(TextView tv)
{
tv.setText("Your AsyncTask was successful!");
return tv;
}
protected void onPostExecute(TextView Result)
{
Context context = context.getApplicationContext();
Toast mytoast = Toast.makeText(context, "AsyncTask processing complete", Toast.LENGTH_LONG);
mytoast.show();
}
}
Obviously AsyncTask IS a generic (http://developer.android.com/reference/android/os/AsyncTask.html#execute(Params...) so why do i get those errors?
There are several problems, two of which are:
You defined a class AsyncTask
, which hides/collides with android.os.AsyncTask
. Maybe you intended to call it AsyncTaskDemo.java or AsyncTaskActivity.java or something.
You're trying to change the UI from the background thread by calling tv.setText
inside of doInBackground
. That defeats the purpose of AsyncTask
. Code in doInBackground
shouldn't be touching the main (or 'UI') thread. For mid-task updates inside of doInBackground
, use AsyncTask.publishProgress
.
You are overriding the AsyncTask methods with the wrong types. It is defined as:
AsyncTask<Params, Progress, Result>
and the doInBackground method is defined as protected abstract Result doInBackground (Params... params)
so according to your definition, you should have protected Void doInBackround(TextView... params);
onPostExecute is also incorrectly defined.
链接地址: http://www.djcxy.com/p/26214.html上一篇: 多次启动/停止服务无法正常工作
下一篇: AsyncTask不是通用的?