Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple input parameters for the method execute() of AsyncTask

everyone. I have read on the android site the description of the excute() of AsyncTask:

public final AsyncTask<Params, Progress, Result> execute (Params... params)

But within my project, I have read the code like this:

private static final int JSON = 0;
private static final int NAME = 1;
@Override
protected String doInBackground(String... strData) {    
       FileOutputTask task = new FileOutputTask(context);
       task.execute(strData[JSON], strData[NAME]);
}

Somebody can tell me why there are 2 input parameters for the execute() method?

Since according the specification, there should be only one input parameter.

Thanks in advance!

like image 498
Mathieu Avatar asked Feb 08 '11 08:02

Mathieu


People also ask

How many times an instance of AsyncTask can be executed?

AsyncTask instances can only be used one time.

What is AsyncTask in java?

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params , Progress and Result , and 4 steps, called onPreExecute , doInBackground , onProgressUpdate and onPostExecute .


2 Answers

Here is how I got it to pass multiple parameters. You could do it as Boris described, but what if you pass different types?

First, create your AsyncTask as normal, but within it, create a constructor:

    private class StartTask extends AsyncTask<Context, Void, Boolean> 
    {
        private ProgressDialog progress;
        private String strAction="";

        public StartTask(ProgressDialog progress, String Action)
        {
            this.progress = progress;
            this.strAction = Action;
        }
    }

Now, on your event or anything else, when you want to kick off the action you call your AsyncTask and pass as many parameters as you want.

    ProgressDialog progress = new ProgressDialog(this);
    progress.setMessage("Loading...");
    String strAction = "this_is_a_string";
    new StartTask(progress, strAction).execute(this);

You can see that calling "StartTask" and passing the constuctor parameters will now assign the variables within the StartTask class.

like image 71
Antebios Avatar answered Jan 01 '23 09:01

Antebios


Read Params... params as Params[] params. You can send as many params as you want.

like image 45
Boris Pavlović Avatar answered Jan 01 '23 08:01

Boris Pavlović