Search code examples
androidspringarraylistresttemplateasyncresttemplate

How to run the same asyn task for each element of my array list?


I have a list that contains elements and i want to send each element of my list seperatly to a local database server using RestTemplate in a AsynkTask.If i specify which element i want to send, i can send it easily and works with my AsyncTask but i want to loop all the list and send all elements one by one to my database..i tried to do a "for loop" inside my AsyncTask but that won't work, i also tried to call the AsyncTask in "for loop" and again nothing happens.. this is my Asynctask using RestTemplate

    private class SendLigneVente extends AsyncTask<LigneVente, Void, LigneVente>{

    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected LigneVente doInBackground(LigneVente... params) {
        try {
            HttpHeaders requestHeaders = new HttpHeaders();
            //solution avec Token
            requestHeaders.add("Content-Type","application/json");
            requestHeaders.add("Accept", "application/json");
            requestHeaders.add("Authorization","Bearer "+AuthToken);
            final String url = StaticUrl+"/api/ligne-ventes";
                RestTemplate restTemplate=new RestTemplate();
                restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
                restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
                LigneVente lv=new LigneVente();
                HttpEntity entity = new HttpEntity(lv, requestHeaders);
                ResponseEntity<LigneVente> response = restTemplate.exchange(url, HttpMethod.POST,entity,LigneVente.class);
                return response.getBody();
        }catch (Exception e) {
            Log.e("ScanActivity", e.getMessage(),e);

        }
        return null;
    }
    protected void onPostExecute(LigneVente result) {
    }
}

and this is when i call my AsyncTask in a for loop :

public void onClick(View v) {
            new CreateVente().execute();
            for(int j=0;j<ligneVentes.size();j++){
                LigneVente lv=ligneVentes.get(j);
            new SendLigneVente().execute(lv);}}

Solution

  • Nothing Is Happenning becausing you are not showing any Feedback in onPostExecute method

    protected void onPostExecute(LigneVente result) {
        Toast.maketext(getContext(),"Uploaded 
        ",Toast.DURATION_SHORT).show();
    }
    

    EDIT : You are not using the params passed to the AsyncTask

    And creating a new object in doInBackground method

    LigneVente lv=params[0];