Akshay Dusane Akshay Dusane - 3 days ago 6
Java Question

Recycler items get loaded after onPostExecute

I am loading data using

Volley
call within an
AsyncTask
. And also did coding to display the
ProgressDialog
. But the problem is
onPreExecute
and
onPostExecute
so fast that
ProgressDialog
do not appear and still the items are not visible after few seconds

Answer

The reason the execution of your AsyncTask looks extremely fast (even faster than you getting the result for your request) is probably that by using Volley inside AsyncTask you are using volley's thread to make the network request instead of the async task thread.

This would make it look like the async task executed really fast, when in fact you just passed the work on to another thread (volley's thread) so AsyncTask concludes its work and you still have nothing, then volley finishes its work and you get the result.

Solution:

Either use Android volley OR use AsyncTask

As you can see in the volley training docs there is no need for AsyncTask

You can also see this SO AsyncTask example and verify that since doInBackgound() runs in another thread, there is no need to use volley or another async method

Update to answer the question in the comments:

How to use ProgressDialog with volley?

It is actually very easy as stated in this other SO post for example

You just have two steps:

  1. You start your ProgressDialog as you add your Volley request to the queue ;)

    //add the request to the queue rq.add(request);

    //initialize the progress dialog and show it
    progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("Fetching The File....");
    progressDialog.show();
    
  2. You dismiss your dialog inside your OnResponse()

    StringRequest postReq = new StringRequest(Request.Method.POST, "http://httpbin.org/post", new Response.Listener<String>() 
    {
    
        @Override
        public void onResponse(String response) {
            tv.setText(response); // We set the response data in the TextView
            progressDialog.dismiss();
        }
    }, 
    
    new Response.ErrorListener() {
    
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.e(“Volly Error”,”Error: ”+error.getLocalizedMessage());
                progressDialog.dismiss();
            }
    });
    
Comments