sdfwer
sdfwer

Reputation: 1042

AsyncTask with parameters of textview

I have an AsyncTask with a textview loaded in the class so it looks something like this:

private class MyClass extends AsyncTask<TextView, Void, Void>{
}
TextView tv;

Loaded this way

"new MyClass(tv).execute();"

The reason for this is because of I have a textview loaded inside a viewflipper and I have a long load method inside the task to implement a process dialog.

My error is found on "protected Void doInBackground(TextView... params) {" this is where params is a TextView[] but not a single TextView.

Does anyone have a solution of to this problem?

Upvotes: 1

Views: 978

Answers (3)

pmckeown
pmckeown

Reputation: 4209

You can't change the method signature of the AsyncTask.doInBackground() method.

It is defined to take a varargs parameter, so you will have to pass a TextView[] parameter to your AsyncTask.

Try Arrays.asList(tv);

If you want to pass a single TextView you will need to define a Construcotr in MyClass and then store the TextView as a field in MyClass. Beware doing this though, you should not hold references to View's or Contexts in your tasks. This will stop the Android OS from garbage collecting the activity that owns the TextView and could leat to a memory leak. If you must keep a reference to a view or context in your AsyncTask, use something like this:

private class MyClass extends AsyncTask<TextView, Void, Void>{ 

    private WeakReference<TextView> tvRef;

    public MyClass(TextView tv) {
        this.tvRef = new WeakReference<TextView>(tv);
    }
}

Upvotes: 3

user
user

Reputation: 87064

Your TextView is the first element in params:

TextView tv = params[0];

NOTE:

If you plan to modify that TextView in doInbackground() don't do it because you'll throw an exception(you can't modify a view from another thread, instead use the onPostExecute method).

Upvotes: 4

Graham Borland
Graham Borland

Reputation: 60681

Just read params[0] as your parameter. You can pass a single value, a sequence or an array wherever you see ... in the parameter list. (A single value is actually a sequence containing just one element.)

Upvotes: 2

Related Questions