适配器不在列表视图中显示数组列表项,但在用于测试的吐司消息中显示字符串

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

我编写此代码是为了从 URL 获取数据并从每个 JSON object 获取标题并将其显示在列表视图中。问题是数据已成功存储在 productlist 变量中,我通过 Log.d 和 Toast 按摩方法对其进行了检查。但它没有显示在列表视图中。

  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();

                }
        }

以下是适配代码 ArrayAdapter arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, productList); myproducts.setAdapter(数组适配器);

您必须使用 notifyDataSetChanged()notifyItemRangeInserted() 通知 adapter 有关 dataset 的更改,如下所示

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();
     }
}

兄弟你没用过notifyDataSetChanged(); 以下是您的操作方法。

ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, productList); 
 myproducts.setAdapter(arrayAdapter);

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();
      Toast.makeText(getApplicationcontext, String.valueOf(productList), Toast.LENGTH_SHORT).show();
 } catch (JSONException e) {
      e.printStackTrace();
 }

}

您必须通过在您的代码中插入此行来让适配器知道列表中的数据已更改:

arrayAdapter.notifyDataSetChanged();

因此您的代码应如下所示:

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();
     }
}