Search code examples
javaandroidandroid-fragmentsasynchronousandroid-asynctask

AsyncTask with ResponseListener


I would like to get data from JSON and doing this in the asyncTask. The problem is that the onPostExecute is executed before the doInBackground.

So here is my fragment where I called the execute :

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    new GetPlantsList().execute();


}

And my AsyncTask

public class GetPlantsList extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected Void doInBackground(Void... voids) {
        Response.Listener<String> responseListener = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                //Si pas d'erreur
                try {
                    // Here my JSON response

                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        };

        //On récupére le fichier php via la variable dans strings.xml et on envoi la requete
        PlantsListRequest plantsListRequest = new PlantsListRequest(user_id, responseListener, getResources().getString(R.string.php_file) + "get_plants_list.php");
        RequestQueue queue = Volley.newRequestQueue(getActivity());
        queue.add(plantsListRequest);
        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);
        // Initialisation de la recycler view (qui va comporter la liste des plantes)
        rv_plants = (RecyclerView) view_frag.findViewById(R.id.rv_list_plants);

        //On vient créer la liste des plantes avec la class Recycler view Plants List (on lui envoie toutes les plantes de mon utilisateurs)
        PlantsList plantsList = new PlantsList(getActivity(), tv_plants_name, tv_plants_variety, iv_plants_img, id_plants);

        //Mon recycler view vient afficher la liste des plantes
        rv_plants.setAdapter(plantsList);
        rv_plants.setLayoutManager(new LinearLayoutManager(getActivity()));
    }

}

In my onPostExecute, I just try to display all the informations that I got from the JSON (and to do this at the end of the request ;)).

I m new in the android programmation. Thanks in advance for your help ;)


Solution

  • The problem is that the onPostExecute is executed before the doInBackground.

    RequestQueue in Volley that operates asynchronously through network threads. thus, onPostExecute is called before the response of plantsListRequest in doInBackground.

    If you want to block thread(task) while network call, you can use RequestFuture. But, it's not recommended. you could simply implement network calls via NetworkQueue with Listener. (without AsyncTask).

    Using RequestFuture

    @Override
    protected Void doInBackground(Void... voids) {
        RequestFuture<String> future = RequestFuture.newFuture();
        
        //On récupére le fichier php via la variable dans strings.xml et on envoi la requete
        PlantsListRequest plantsListRequest = new PlantsListRequest(user_id, future, getResources().getString(R.string.php_file) + "get_plants_list.php");
        RequestQueue queue = Volley.newRequestQueue(getActivity());
        queue.add(plantsListRequest);
    
        String response = future.get(); // blocking thread
    
        return null;
    }
    

    Volley

    volley - request

    Reference