【问题标题】:Updating List <HashMap>更新列表 <HashMap>
【发布时间】:2011-04-23 10:50:41
【问题描述】:

我只想知道如何,如果 Hashmap 已经在列表中,则将数量加 1,如果没有,则将其添加到列表中。这就是我所做的,即使该项目已经在列表中,也只是添加。

list = new ArrayList<HashMap<String, String>>();
Cursor c = db.rawQuery("SELECT code,desc,price FROM TbLPrice WHERE code =" + txtCode.getText().toString(), null);  //search database
                if (c.moveToFirst()){ //if successful
                    txtDesc.setText(c.getString(1)); //get desc 
                    txtPrice.setText(c.getString(2)); // get price @ database
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("desc", c.getString(1));
                    map.put("price", c.getString(2));
                    map.put("quantity","1");
                    list.add(map);
                    adapter.notifyDataSetChanged();

【问题讨论】:

  • 你真正想用这个实现什么?如果您解释要解决的问题,可能会更容易理解您的代码。因为到目前为止,它没有多大意义......
  • 请看下面我的解决方案。在列表中添加项目之前,我想知道它是否已经存在,如果不存在,则将项目添加到列表中,如果已经存在,则将其 hashmap“数量”更新为 2,依此类推。
  • 在写我的第一条评论时,我已经在下面查看了您的解决方案。我再说一遍:你真正想用这个实现什么?你的代码不容易阅读(而且看起来代码是更大上下文的一部分),所以很难理解,因此很难帮助你。例如,为什么在“ArrayList”中有几个“HashMap”?您是否尝试总结一些东西?因为如果是这种情况,我觉得我错过了一个循环或其他东西......尝试清理你的代码并澄清你的问题(也许有一个具体的例子),那么我们也许可以帮助你。
  • 对不起我的代码。我还是安卓新手。我有一个列表,它将存储带有 [desc,price,quantity] 的哈希图。我想在列表中添加一个元素,但在添加之前,我想先检查相同的项目是否存在,因为它是否已经存在。我不会添加另一个元素,但会更新同一项目的数量。前任。 DESC PRICE QUANTITY ITEM A 10.00 1 ITEM B 20.00 1 如果我想添加另一个 ITEM A,它已经存在于列表中,所以我只想将 1 添加到列表中已经存在的 Item A 的数量。

标签: android list hashmap


【解决方案1】:

我想出了这个解决方案,但是如果一个项目存在,它只会在第 3 次尝试更新数量 2 次它会创建具有相同描述、价格但数量为 1 的新列表项目。

Cursor c = db.rawQuery("SELECT code,desc,price FROM TbLPrice WHERE code =" + txtCode.getText().toString(), null);  //search database
            if (c.moveToFirst()){ //if successful
                txtDesc.setText(c.getString(1)); //get desc 
                txtPrice.setText(c.getString(2)); // get price @ database
                HashMap<String, String> map = new HashMap<String, String>();
                map.put("desc", c.getString(1));
                map.put("price", c.getString(2));

if(list.isEmpty()){
                    map.put("quantity","1");
                    list.add(map);
                    adapter.notifyDataSetChanged();
                }
                else{
                    if(list.contains(map)){
                        int loc = list.indexOf(map);
                        Object o = list.get(loc);
                        @SuppressWarnings("unchecked")
                        HashMap<String, String> map2 = (HashMap<String, String>)o;
                        String b = (String) map2.get("quantity");
                        int quantity = Integer.parseInt(b) + 1;
                        map2.put("quantity", Integer.toString(quantity));
                        adapter.notifyDataSetChanged();

                    }
                    else{
                        map.put("quantity","1");
                        list.add(map);
                        adapter.notifyDataSetChanged();
                    }

【讨论】:

    【解决方案2】:

    从您上次的评论中,我想我明白您要做什么。首先,我将创建一个包含您的项目信息的小类,以使其更易于使用(我只实现了必要的设置器,您可能还需要一些获取器(和其他功能)):

    public class MyItem
    {
        String description;
        float price;
        int quantity;
    
        public void setDescription(String description)
        {
            this.description = description;
        }
    
        public void setPrice(float price)
        {
            this.price = price;
        }
    
        public void setQuantity(int quantity)
        {
            this.quantity = quantity;
        }
    
        public void increaseQuantity()
        {
            this.quantity++;
        }
    
        @Override
        public int hashCode()
        {
            final int prime = 31;
            int result = 1;
            result = prime * result + ((description == null) ? 0 : description.hashCode());
            return result;
        }
    
        @Override
        public boolean equals(Object obj)
        {
            if (this == obj)
                return true;
            if (obj == null)
                return false;
            if (getClass() != obj.getClass())
                return false;
            MyItem other = (MyItem) obj;
            if (description == null)
            {
                if (other.description != null)
                    return false;
            }
            else if (!description.equals(other.description))
                return false;
            return true;
        }
    }
    

    我已经实现了equals 方法(并且通常还实现hash 方法)以便能够轻松检查列表中是否存在项目(为简单起见,我假设description唯一标识一个项目,您应该根据需要进行更改)。然后您可以像这样继续处理:

    public void queryForItem(String itemCode)
    {
        Cursor cursor = db.rawQuery("SELECT code,desc,price FROM TbLPrice WHERE code =" + itemCode, null);
        if (cursor.moveToFirst())
        {
            processCursor(cursor);
        }
        cursor.close();
    }
    
    private void processCursor(Cursor c)
    {
        MyItem newItem = new MyItem();
        newItem.setDescription(c.getString(1));
        newItem.setPrice(c.getFloat(2));
        newItem.setQuantity(1);
    
        // assuming that items (ArrayList<MyItem>) is defined and initialized earlier in the code
        int existingItemIndex = items.indexOf(newItem);
        if (existingItemIndex >= 0)
        {
            items.get(existingItemIndex).increaseQuantity();
        }
        else
        {
            items.add(newItem);
        }
        adapter.notifyDataSetChanged();
    }
    

    我没有以任何方式对此进行测试,但我认为它应该可以满足您的需求。希望你能看到其中的逻辑:)

    【讨论】:

    • 感谢您的帮助,但我的数组列表声明为:list = new ArrayList>(); list.get(existingItemIndex).increaseQuantity(); 出现错误
    • 我试图申请,但仍然。它仅在第三次创建新的相同列表项时更新 2 次。我认为如果项目存在,搜索就会出现逻辑错误。因为在代码上。它使用项目 A 搜索列表,数量 = 1,因此在更新到项目 A 后,数量 = 2。它无法搜索数量为 1 的项目 A,因此它创建了一个新的列表项目 A,数量 = 1 等等
    • 我建议将您的ArrayList&lt;HashMap&lt;String, String&gt;&gt; 替换为ArrayList&lt;MyItem&gt;,您可以在其中使用自定义MyItem,而不必乱用HashMap 中的值。检查列表中是否已存在项取决于MyItemequals 方法的实现。正如我所写,为简单起见,我使用description 来比较两个项目,但您可能希望更改它(例如使用 ID)。还请记住,不要重新创建列表或其他任何使其在程序中某个时间点重置的内容...
    • 你能告诉我 hashcode() 和 equals(Object obj) 是做什么的吗?我想我错过了那部分
    • equalshashCode 是基本的 Java 知识,因此我建议您阅读此内容 :) 如果您想正确检查重复项/现有项目,则需要覆盖 equals自定义项目列表。你可以在这里阅读更多关于它们的信息ibm.com/developerworks/java/library/j-jtp05273.html 或者干脆用谷歌搜索“java equals hashcode”
    猜你喜欢
    • 2017-10-01
    • 2021-05-22
    • 1970-01-01
    • 2012-11-16
    • 2012-01-10
    • 1970-01-01
    • 1970-01-01
    • 2011-10-09
    • 2016-09-12
    相关资源
    最近更新 更多