Vamsi Challa Vamsi Challa - 6 months ago 18
Android Question

How to pass values to AsyncTask Android

This is the first time i am using AsyncTask and probably a little confused as well, about passing the values.

I have 4

ArrayList<String>
s, which contain data that should be inserted into the database. I want this insertion to be done in background. There will be a minimum of 50 rows to be inserted into the database and 1 row is inserted at a time, by taking passing values from 4 arraylists that i have.

Can someone guide me on how to do this?

Now i create a subclass InsertData that extends AsyncTask :::

private class InsertData extends AsyncTask<Params, Progress, Result>{

@Override
protected Result doInBackground(Params... params) {
// TODO Auto-generated method stub
return null;
}
}


I have values in 4 arraylists, in which i need to retrieve 1 entry from each arraylist and pass the 4 values to the database. How do i pass these 4 values to the AsyncTask and also, how do i repeat this till there are entries in the arraylists.

Here is the database method that inserts 1 row into the database :::

public void insert_row(int count, String image_url, String name, String number) {
// TODO Auto-generated method stub

db.execSQL("INSERT INTO contacts VALUES('"+ count +"', '"+ image_url +"', '"+ name +"', '"+ number +"')");
}


If someone can give me a overview on how i can implement this, It would be great.

Answer

Try the following, and, anyway, you could create constructor for InsertData with parameters you need, store them in InsertData class fields and use in doInBackground().

private class InsertData extends AsyncTask<ArrayList, Progress, Result>{

            @Override
            protected Result doInBackground(ArrayList... params) {
                // TODO Auto-generated method stub
                ArrayList list1 = params[0];
                ArrayList list2 = params[1];
                ...
                return null;
            }   
    }

Call:

InsertData task = new InsertData();
task.execute(yourList1, yourList2, yourList3...);