I want to insert records into a database, but iterate through a list. and in each tour insert the record.
can the asynctask be run inside a for? any help please.
I want to insert records into a database, but iterate through a list. and in each tour insert the record.
can the asynctask be run inside a for? any help please.
It does not make much sense to go through a loop opening threads and communicate with the server in each of them, as a very large loop is going to fail. Instead, you can pause that list and send it to the server in a single call.
Read more about the AsyncTask, in the documentation you have an example, I would recommend you even make your own examples, you are orienting it badly.
The doInBackground method is responsible for performing all the tasks that you send in the background, the what and the how is totally indifferent.
You have to bear in mind that AsyncTask
executes a thread in the background of your application. It is not at all recommended that for each insertion in your database you create a new hilo
in the background, the optimal thing is to create an asynchronous task that runs through all the records and makes the corresponding inserts
.
With AsyncTask
you have the facility to send parameters to your task and manage them.
The order is more or less like that
private class Insert extends AsyncTask<A, B, C>
Where:
doInBackground
The method doInBackground
is the one for me, more important in an asynchronous task since it is responsible for executing all your code, here should be all the logic of your task in the background. Therefore it is HERE where you should receive your arrangement, object, list of the data that you want to insert in your database. This is where you have to do for
to go through and insert them.
If in your case it is a List<>
that you want to send per parameter and it should be
private class Insert extends AsyncTask<ArrayList<String>, B, C>
protected int doInBackground(ArrayList<String>... listaParametro) {
int result = 1;
try{
for (int i=0; i<listaParametro.size(); i++) {
System.out.println(listaParametro.get(i)); //Elemento iterado
}
}catch (Exception e){
result = 0;
}
return result;
}
onProgressUpdate
onPostExecute
The onPreExecute
method does not have parameters since it is executed before starting your task, you can initialize variables.