user3289108
user3289108

Reputation: 770

Listview is empty after getting data through Volley?

I'm just doing a basic Async Task that fetches the data through Volley Library. The problem i'm facing is that, listview is always empty even the arrayList contains some values.

public class MainActivity extends AppCompatActivity  {

    String url = "...";
    String tag_json_obj = "json_obj_req";
    ProgressDialog pDialog;
    String TAG = MainActivity.class.getSimpleName();
    ListView listView;
    ArrayList<String> stringArrayList;
    ArrayAdapter<String> adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        listView = (ListView)findViewById(R.id.listView);
        stringArrayList = new ArrayList<String>();
        new Volleyoperation().execute();

    }





    public class Volleyoperation extends AsyncTask<Void, Void, ArrayList<String>> {

        ArrayList<String> arrayList = new ArrayList<>();

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(MainActivity.this);
            pDialog.setTitle("Volley Operation");
            pDialog.setMessage("Loading...");
            pDialog.show();
        }

        @Override
        public ArrayList<String> doInBackground(Void... voids) {

            JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
                    url, (String)null,
                    new Response.Listener<JSONObject>() {

                        @Override
                        public void onResponse(JSONObject response) {
                            Log.d(TAG, response.toString());

                            try {
                                JSONArray jsonArray = response.getJSONArray("posts");
                                for (int i = 0; i < jsonArray.length(); i++){
                                    JSONObject object = jsonArray.getJSONObject(i);
                                    Log.d("track", "" + object.getString("title_plain"));

                                    stringArrayList.add(object.getString("title_plain"));
                                }

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


                            Log.d("track", "done");
                           // pDialog.hide();
                        }
                    }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) {
                    VolleyLog.d(TAG, "Error: " + error.getMessage());
                   VolleyLog.d(TAG, "error msg" +error.networkResponse);
                    Log.d("track", "Error");

                    if(error.networkResponse == null){
                        Log.d("track","Time out");
                    }

                    // hide the progress dialog
              //      pDialog.hide();
                }
            });

            jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(5000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));

            AppController.getInstance().addToRequestQueue(jsonObjReq, tag_json_obj);
            return stringArrayList;
        }

        @Override
        protected void onPostExecute(ArrayList<String> result) {
            super.onPostExecute(result);
            Log.d("trrrrr", "on post execute");

            adapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, stringArrayList);
            listView.setAdapter(adapter);
            pDialog.hide();
        }
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }


}

Logcat :

08-09 14:46:26.820    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Monsoon mocktails
08-09 14:46:26.820    3207-3207/com.yuvaraj.volleytutorial D/track﹕ MANDAVELLI MARKET
08-09 14:46:26.821    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Full Volume &#8211; Musical Game and Karaoke Night
08-09 14:46:26.821    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Bake frost and decorate fondant cake
08-09 14:46:26.821    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Purasawalkam Food Ride
08-09 14:46:26.821    3207-3207/com.yuvaraj.volleytutorial D/track﹕ LIFESTYLE SHOPPING FEST 2015
08-09 14:46:26.822    3207-3207/com.yuvaraj.volleytutorial D/track﹕ DANCE FOR LIFE‬
08-09 14:46:26.822    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Act Fast
08-09 14:46:26.822    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Yes, I Will &#8211; The Stage Fright Cure Workshop
08-09 14:46:26.822    3207-3207/com.yuvaraj.volleytutorial D/track﹕ Murphy&#8217;s Wedding
08-09 14:46:26.822    3207-3207/com.yuvaraj.volleytutorial D/track﹕ done

I couldn't find where I'm making the mistake.

Upvotes: 2

Views: 653

Answers (3)

hasan
hasan

Reputation: 24205

As in Simon answer, you are no waiting for the array list to get filled before setting the adapter.

This can be solved by moving the Json parsing fro doInBackground method to onPostExecute method. and set the adapter in the onResponse method.

That's a better practice anyway.

Upvotes: 1

HassanUsman
HassanUsman

Reputation: 1973

You used two Asynchronous methods so thats why ListView not displaying any data.

Use only one Async Task

Upvotes: 0

Simon Marquis
Simon Marquis

Reputation: 7516

You are using an asynchronous method inside an asynchronous method, and therefore you don't wait for the result in your AsyncTask.

JsonObjectRequest is already an asynchronous methods, and you simply have to use the corresponding callbacks onResponse and onErrorResponse to dispatch the result.

TLDR; in this particular example, don't use AsynTask with an async network request

Upvotes: 2

Related Questions