Frage

I want to make a base class for some aSyncTasks. I've created an abstract class

public abstract class AsyncTaskBase<Params, Progress, Result> extends
    AsyncTask<Params, Progress, Result> {}

And two AsyncTask classes which inherit from it aSyncTaskA:

public class AsyncTaskA extends AsyncTaskBase<String, String, String> {

    @Override
    protected String doInBackground(String... params) 
    {
        return "A";
    }
}

And two AsyncTask classes which inherit from it aSyncTaskB:

public class AsyncTaskB extends AsyncTaskBase<String, String, String> {

    @Override
    protected String doInBackground(String... params) 
    {
        return "B";
    }

}

In the calling method I call:

AsyncTaskBase asyncTask;

// Call aSyncA
asyncTask = new AsyncTaskA();
asyncTask.execute();

// Call aSyncB
asyncTask = new AsyncTaskB();
asyncTask.execute();

But I get the following error message

05-02 17:00:18.674: E/AndroidRuntime(20120): Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.lang.String[]

Any ideas what's going wrong

War es hilfreich?

Lösung

The error is occurring because you haven't passed any params to the AsyncTask when you call #execute(). You declare that the AsyncTask takes params of type String, but you don't pass in anything at all.

You'll need to call #execute like this:

asyncTask.execute( (String) null );

or this:

asyncTask.execute( (String[]) null );

or change the generic type for the Params to Void if you want to call #execute without any parameters.


Also, it's kind of pointless to declare the exact base async that you have demonstrated here. I assume you'll add something to it at some point, but I think you would be better served by having a base async that at least took care of the generic type parameters for you, i.e. -

public abstract class BaseHttpAsync extends AsyncTask<Uri, Void, HttpResult>

Declaring public abstract class AsyncTaskBase<Params, Progress, Result> extends AsyncTask<Params, Progress, Result> {} effectively gains you no benefits.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top