【问题标题】:Problem with Arraylist and Hashmap, outputs 35 times the same lineArraylist 和 Hashmap 的问题,同一行输出 35 次
【发布时间】:2019-10-16 20:17:51
【问题描述】:

我正在尝试使用我的 JSON 文件中的数据填充我的 Listview。但由于某种原因,它只将同一行输出到列表视图中的 35 倍。有人知道为什么吗?

JSONArray json = new JSONArray(data);
                ArrayList<HashMap<String, String>>  arrayList = new ArrayList<HashMap<String, String>>();

                HashMap<String, String> map = new HashMap<String, String>();
                try {
                for(int i=0;i<json.length();i++){
                    JSONObject e =json.getJSONObject(i);
                    map.put("id", String.valueOf(i));
                    map.put("Name", "Vorname: " + e.getString("meta_value"));
                    map.put("orderid", "id: " + e.getString("post_id"));
                    arrayList.add(map);
                }
final ArrayAdapter arrayAdapter = new ArrayAdapter(activity2.this, android.R.layout.simple_list_item_1,arrayList);

                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        ListView myListView = (ListView) findViewById(R.id.list);
                        myListView.setAdapter(arrayAdapter);
                    }
                });

【问题讨论】:

标签: java android arrays hashmap


【解决方案1】:

Java 中所有对象类型的变量都是引用变量,重要的是要区分设置引用变量(使用=)和操作变量引用的对象(使用一些变异方法)。

在这里,您已将 map 设置为存储对您的 HashMap 的引用。然后,在您的循环中,您一遍又一遍地将相同的引用 map 添加到 arrayList。当您检查arrayList 时,其中有多个map 副本,但它们都是相等的。因此,您将一遍又一遍地看到当时HashMap 中发生的任何事情。你只创建了一个HashMap;每次你将"id""Name""orderid" 放入HashMap 时,你只是覆盖了之前的内容。

要解决此问题,您需要在每次循环中创建一个新的HashMap。您要做的是在循环之前声明 map,但在循环内分配它,每次都分配给一个新对象。

HashMap<String, String> map;
try {
    for(int i=0;i<json.length();i++){
        map = new HashMap<String, String>();
        e =json.getJSONObject(i);
        map.put("id", String.valueOf(i));
        map.put("Name", "Vorname: " + e.getString("meta_value"));
        map.put("orderid", "id: " + e.getString("post_id"));
        arrayList.add(map);
    }

【讨论】:

    【解决方案2】:

    目前,您正在为数组的每个元素分配相同的对象。

    for 循环内移动地图的创建,并使用该作用域变量进行操作,然后将其添加到数组中。

     try {
                for(int i=0;i<json.length();i++){
                    HashMap<String, String> map = new HashMap<String, String>();
                    JSONObject e =json.getJSONObject(i);
                    map.put("id", String.valueOf(i));
                    map.put("Name", "Vorname: " + e.getString("meta_value"));
                    map.put("orderid", "id: " + e.getString("post_id"));
                    arrayList.add(map);
                }
    

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 2020-02-13
      • 2011-09-13
      • 1970-01-01
      • 1970-01-01
      • 2019-04-16
      • 1970-01-01
      • 1970-01-01
      • 2017-03-24
      相关资源
      最近更新 更多