Flo
Flo

Reputation: 187

Casting AsyncTask in Android

I have two AsyncTasks in my activity that use different argument types each:

private class TaskA extends AsyncTask<Void, byte[], Boolean> { ... }
private class TaskB extends AsyncTask<byte[], byte[], Boolean>

Both sub classes implement a method public boolean SendDataToNetwork(final byte[] cmd) which can be called from the gui thread.

I'd like to have a reference in my activty that points to either TaskA or TaskB depending on which arguments get passed to my activity with an intent.

What I did try so far is:

private AsyncTask<?, ?, ?> myTask = null;

and

 switch(mode) {
    case 1: 
        myTask = new TaskA();
        break;
    case 0:
        myTask = new TaskB();
        break;
    }

However, when I try to execute myTask later in the code with

myTask.execute();

this leads to a compile error: Type safety: A generic array of capture#7-of ? is created for a varargs parameter

How can I properly cast myTask to TaskA or TaskB according to the switch-case statement?

Update:

Initializing myTask with:

private AsyncTask myTask = null;

yields to one warning:

myTask= new TaskA();
myTask.execute();

The method execute(Object...) belongs to the raw type AsyncTask. References to generic type AsyncTask<Params,Progress,Result> should be parameterized

If I try to use the method SendDataToNetwork I get an error now:

The method SendDataToNetwork(byte[]) is undefined for the type AsyncTask

It looks like the object myTask is never really casted to the type TaskA or TaskB?

Upvotes: 0

Views: 1717

Answers (1)

Sparky
Sparky

Reputation: 8477

If you are counting on being able to call SendDataToNetwork on both task types, perhaps your AsyncTask subclasses should implement an Interface that declares it.

Upvotes: 1

Related Questions