Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing parameters to Asynctask

I am using Async tasks to get string from the menu activity and load up some stuff..but i am not able to do so..Am i using it in the right way and am i passing the parameters correctly? Please see the code snippet. thanks

  private class Setup extends AsyncTask<Void, Integer, Void> {

    @Override
    protected Void doInBackground(Void... params) {
        try {
            if (!(getIntent().getExtras().isEmpty())) {
                Bundle gotid = getIntent().getExtras();
                identifier = gotid.getString("key");
            }
        } catch (Exception e) {
            e.getStackTrace();
        } finally {

            if (identifier.matches("abc")) {
                publishProgress(0);
                db.insert_fri();
            } else if ((identifier.matches("xyz"))) {
                publishProgress(1);
                db.insert_met();
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... i) {
        // start the song here
        if (i[0] == 0) {
            song.setLooping(true);
            song.start();
        }
    }

    @Override
    protected void onPostExecute(Void res) {

    }

    @Override
    protected void onPreExecute() {
        // do something before execution
    }
}
like image 651
Nikhil Avatar asked Sep 03 '11 17:09

Nikhil


1 Answers

Avoid adding a constructor.

Simply pass your paramters in the task execute method

new BackgroundTask().execute(a, b, c); // can have any number of params

Now your background class should look like this

public class BackgroundTask extends AsyncTask<String, Integer, Long> {

    @Override
    protected Long doInBackground(String... arg0) {
        // TODO Auto-generated method stub
        String a = arg0[0];
        String b = arg0[1];
        String c = arg0[2];
        //Do the heavy task with a,b,c
        return null;
    }
    //you can keep other methods as well postExecute , preExecute, etc

}
like image 110
HimalayanCoder Avatar answered Oct 20 '22 17:10

HimalayanCoder