Search code examples
javaandroidapilistviewandroid-volley

The adaptor not showing the Array list items in List view but show the string in Toast msg which used for test


I write this code to fetch data from URL and get the title from each JSON object and show this in the list view. The problem is data is stored successfully in productlist variable, which I check it by Log.d and Toast massage method. but it not show in listview.

  public void onResponse(JSONArray response) {
            try {
                    for(int i=0;i<response.length();i++) {
                        JSONObject productfromjson = response.getJSONObject(i);
                        productList.add(productfromjson.getString("title"));
                    }
                    Log.d("products", String.valueOf(productList));
                    Toast.makeText(MainActivity.this, String.valueOf(productList), Toast.LENGTH_SHORT).show();
                } catch (JSONException e) {
                    e.printStackTrace();

                }
        }

the following is the adaptor code ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, productList); myproducts.setAdapter(arrayAdapter);


Solution

  • You have to notify adapter about dataset changes using notifyDataSetChanged() or notifyItemRangeInserted() like below

    public void onResponse(JSONArray response) {
         try {
             for(int i=0;i<response.length();i++) {
                 JSONObject productfromjson = response.getJSONObject(i);
                 productList.add(productfromjson.getString("title"));
              }
              arrayAdapter.notifyDataSetChanged();
              Log.d("products", String.valueOf(productList));
              Toast.makeText(MainActivity.this, String.valueOf(productList), Toast.LENGTH_SHORT).show();
         } catch (JSONException e) {
              e.printStackTrace();
         }
    }