How to add Asynctask to this task?

Asked

Viewed 51 times

0

Hi, could someone help me add an Asynctask to this task? Here I am connecting to a JSON for information, then it will be added to Recyclerview.

RequestQueue queue = Volley.newRequestQueue(this);
        String shhik = "http://meusite/arquivo.json";
        StringRequest stringRequest = new StringRequest(Request.Method.GET, shhik, new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                Log.d(TAG, "Response " + response);
                GsonBuilder builder = new GsonBuilder();
                Gson mGson = builder.create();
                List<receive_info> posts = new ArrayList<receive_info>();
                posts = Arrays.asList(mGson.fromJson(response, receive_info[].class));
                adapter = new adapter_info(Main.this, posts);
                recyclerView.setAdapter(adapter);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(getApplicationContext(), "Erro ao tentar conectar com servidor!", Toast.LENGTH_SHORT).show();
                Log.d(TAG, "Error " + error.getMessage());
            }
        });
        queue.add(stringRequest);
    }

Thank you very much!

  • Why you want to add an Asynctask? queue.add(stringRequest); already runs the request asynchronously.

  • @ramaral Hello friend! Thank you for answering. So I want to add an Asynctask, so I show the user a progressiBar, Alertdialog..

1 answer

3

No need to add a Asynctask to be able to show a Progressbar.
The Volley processes the request asynchronously.

From this perspective and by comparison to Asynctask, the method onResponse(), or the onErrorResponse() if there is an error, it corresponds to the method onPostExecute().
What to put before queue.add(stringRequest); "corresponds" to be placed in the onPreExecute().

Thus, you should start the Progressbar in the line before queue.add(stringRequest); and finish it in the methods onResponse() and onErrorResponse().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.