views:

104

answers:

3

I just want to know how to, if a Hashmap is already on the list add 1 to quantity, if it is not then add it to list. This is what I've done that just add eventhough the item is already on list.

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

I came up with this solution, however if an item exist it only update the quantity 2 times on 3rd try It creates new list item with same desc, price but 1 quantity.

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();
                    }
John Paul
A: 

From your last comment, I think I see what you're trying to do. Firstly, I would create a small class holding the information about your items, to make it a bit easier to work with (I've only implemented the necessary setters, you'll probably want some getters (and other functions) as well):

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

I have implement the equals method (and it is common to then also implement the hash method) to easily be able to check if an item exists in the list (for simplicity, I assume that the description uniquely identifies an item, you should change this as needed). You can then continue with your processing like this:

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

I haven't tested this in any way, but I thing it should do what you want. Hope you're able to see the logic in it :)

Nailuj
thanks for the help, but my arraylist is declared as this : list = new ArrayList<HashMap<String, String>>(); got errors on the list.get(existingItemIndex).increaseQuantity();
John Paul
I'll try to modify and apply this to my code . thanks .
John Paul
I tried to apply but still. it only updates 2 times on the third time it creates a new same list item. I think the logical error comes on the search if item exists. because on the code. it searches the list with item A, quantity = 1, so after it updates to item A, quantity = 2. it cant search item A with quantity 1 so it creates a new list item A, quantity = 1 and so on
John Paul
I suggested to replace your `ArrayList<HashMap<String, String>>` with an `ArrayList<MyItem>`, where you use the custom `MyItem` instead of having to mess around with values in a `HashMap`. Checking whether an item already exists in the list depends on the implementation of the `equals` method in `MyItem`. As I wrote, for simplicity I use the `description` to compare two items, but you would perhaps like to change that (to use an ID for instance). Also remember to be make you don't re-create the list or anything else that makes it reset at some point in your program...
Nailuj
can you tell me what hashcode() and equals(Object obj) does.i guess i'm missing that part
John Paul
`equals` and `hashCode` are basic Java knowledge, so I recommend reading up on this :) Overriding `equals` is for instance necessary if you want to correctly check for duplicates/existing items in your list of custom items. You can read more about them here http://www.ibm.com/developerworks/java/library/j-jtp05273.html or simply google for "java equals hashcode"
Nailuj
A: 

Sorry I'm a noob. now I got problems showing the values in the listview. This is how I adapt my list to the listview earlier when I use Arraylist, now I dont know what to do .

itemList = (ListView) findViewById(R.id.list);
 adapter = new SimpleAdapter(this, (List<? extends Map<String, ?>>) list, R.layout.list_item,
                new String[] {"description","price","quantity"}, new int[] {R.id.listdesc, R.id.listprice,R.id.listquantity});
        itemList.setAdapter(adapter);

R.layout.list_item looks like this.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
     android:paddingTop="4dip"
     android:paddingBottom="6dip"

     android:orientation="horizontal" android:layout_width="wrap_content" android:layout_height="wrap_content">

        <TextView
        android:focusable="false"

            android:text="Item" 
            android:id="@+id/listdesc"
            android:layout_height="wrap_content" android:layout_width="130dip"/>

        <TextView
        android:focusable="false"

            android:text="Price" 
            android:id="@+id/listprice"
            android:layout_height="wrap_content"
            android:layout_width="130dip"
            android:layout_weight="1" />

        <TextView
        android:focusable="false"

            android:text="Quantity" 
            android:id="@+id/listquantity"
            android:layout_height="wrap_content"
            android:layout_weight="1" android:layout_width="wrap_content"/>

</LinearLayout>
John Paul
New questions should be posted as _new_ question, and not as answers to an existing questions. It is not likely people will even see this, as it is inside a question with an already accepted answer.
Nailuj