简体   繁体   English

ArrayList添加和删除对象

[英]ArrayList adding and removing Objects

I'm working on an android application where I have to use custom listview with checkboxes. 我正在使用必须使用自定义listview和复选框的android应用程序。 When user checks/unchecks, I need to add/remove objects in array list respectively. 当用户选中/取消选中时,我需要分别在数组列表中添加/删除对象。

here is my code: 这是我的代码:

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
    selectedView=view;
    System.out.println("Position of list item:"+position);
    if(parent.getAdapter().equals(categoryAdapter))
    {       
        System.out.println("First Adapter");        
        fl=new FoodList();      
        System.out.println("Tag:"+view.getTag());
        btOrder.setVisibility(View.GONE);
        addToOrder.setVisibility(View.VISIBLE);
        back.setVisibility(View.VISIBLE);
        buttonSeperator.setVisibility(View.VISIBLE);


        fl.bundleCategory=fc.list[position];        
        fl.foodListService();       
        checks=new SparseBooleanArray();        
        quantity=new SparseArray<Integer>();

        orderList=new ArrayList<Order>();
        order=new Order();
        Order Null=null;
        for(int i=0;i<fl.foodList.size();i++)
        {
            checks.put(i, false);
            quantity.put(i, 0);
            order.setQuantity(0);
            order.setItem("");
            //orderList.add(i,Null);
            //orderList.add(i,order);
            orderList.add(order);
            System.out.println("Adding at pos:"+i+"Value:"+Null);
        }   
        WaiterFoodAdapter foodAdapter=new WaiterFoodAdapter(this, R.layout.take_order_list, fl.foodList);
        categoryList.setAdapter(foodAdapter);
        categoryList.setOnItemClickListener(this);
        }
        else
        {           
            System.out.println("Second Adapter:Id="+parent.getId());

            if(view != null)
            {
                final TextView tvItem=(TextView)selectedView.findViewById(R.id.foodName);   
                final TextView tvQuantity=(TextView)selectedView.findViewById(R.id.quantity);

                selectedPosition=position;
                SelectFood = (CheckBox)view.findViewById(R.id.selectFood);

                if(SelectFood.isChecked())          
                {           
                    SelectFood.setChecked(false);                   
                    checks.put(selectedPosition, false);
                    quantity.put(selectedPosition,0);

                    //order.setQuantity(0);
                    //order.setItem("");
                    System.out.println("Removing at pos:"+selectedPosition+"Value:"+orderList.get(selectedPosition).getItem()+orderList.get(selectedPosition).getQuantity());
                    orderList.remove(orderList.get(selectedPosition));

                    tvQuantity.setText("0");
                    System.out.println("Position="+selectedPosition);
                }           
                else
                {
                    SelectFood.setChecked(true);                    
                    checks.put(selectedPosition, true);
                    System.out.println("Position="+selectedPosition);

                    //orderList=new ArrayList<Order>();                     
                    final AlertDialog.Builder quantityAlert= new AlertDialog.Builder(TakeOrder.this);
                    quantityAlert.setTitle("Quantity");
                    quantityAlert.setMessage("Please enter quantity");

                    final EditText input = new EditText(TakeOrder.this);
                    input.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
                    quantityAlert.setView(input);

                    quantityAlert.setPositiveButton("Ok", new DialogInterface.OnClickListener()
                    {   
                        public void onClick(DialogInterface dialog, int whichButton)
                        {
                            value = input.getText();



                            if(value.toString().equals(""))
                            {               
                                SelectFood.setChecked(false);
                                Toast msg=Toast.makeText(TakeOrder.this, "Please provide quantity", Toast.LENGTH_SHORT);
                                msg.show();       
                            }
                            else
                                if(value.toString().equals("0"))
                                {                       
                                    SelectFood.setChecked(false);                        
                                    Toast msg=Toast.makeText(TakeOrder.this, "Please enter valid quantity", Toast.LENGTH_SHORT);                          
                                    msg.show();
                                }
                                else                    
                                {                                   
                                    tvQuantity.setText(value);
                                    quantity.put(selectedPosition, Integer.valueOf(value.toString()));
                                    order.setQuantity(Integer.valueOf(tvQuantity.getText().toString()));
                                    order.setItem(tvItem.getText().toString());
                                    orderList.add(selectedPosition, order);
                                    System.out.println("setting at pos:"+selectedPosition+"Value:"+orderList.get(selectedPosition).getItem()+orderList.get(selectedPosition).getQuantity());
                                }



                            //Log.v("Item:",orderList.get(selectedPosition).getItem());
                            //Log.v("Quantity:",String.valueOf(orderList.get(selectedPosition).getQuantity()));

                        }               
                    });

                quantityAlert.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
                {
                      public void onClick(DialogInterface dialog, int whichButton)
                      {
                          SelectFood.setChecked(false);                
                      }
                    });

                quantityAlert.show();
            }                                           
        }

    }

}

When user click addToOrder button it just search for checked checkboxes and gettin relevant textViews values of checked listItems.. 当用户单击addToOrder按钮时,它仅搜索选中的复选框,并获取选中的listItems的相关textViews值。

public void addToOrder(View v)
{
    for(int i=0;i<fl.foodList.size();i++)
    {           
        if(checks.get(i)==true)
            {
            System.out.println("Order is:"+orderList.get(i).getItem()+orderList.get(i).getQuantity());
            }                   
    }
}

this is my adapter which is just for custom view purpose 这是我的适配器,仅用于自定义视图

public class WaiterFoodAdapter extends ArrayAdapter<Food> 
{
    Context context;
    TakeOrder holder;
    int layoutResourceId;
    List<Food> foodList;

    public WaiterFoodAdapter(Context context, int layoutResourceId,List<Food> foodList)
    {
        super(context, layoutResourceId, foodList);         
        this.context=context;
        this.layoutResourceId=layoutResourceId;
        this.foodList=foodList;
    }

    @Override
    public View getView(int position,View convertView,ViewGroup parent)
    {
        View row=convertView;

        if(row==null)
        {
            LayoutInflater inflater=((Activity)context).getLayoutInflater();
            row=inflater.inflate(layoutResourceId, parent,false);
            holder=new TakeOrder();
            holder.foodIcon=(ImageView)row.findViewById(R.id.foodIcon);
            holder.tvFoodName=(TextView)row.findViewById(R.id.foodName);
            holder.cbSelectFood=(CheckBox)row.findViewById(R.id.selectFood);
            holder.cbSelectFood.setClickable(false);             
            holder.tvFoodDescription=(TextView)row.findViewById(R.id.foodDescription);
            holder.tvFoodQuantity=(TextView)row.findViewById(R.id.foodQuantity);
            holder.tvQuantity=(TextView)row.findViewById(R.id.quantity);
            row.setTag(holder);

        }       
        else
        {               
            holder=(TakeOrder)row.getTag();             
        }
        if(fl.bundleCategory.equals("Appetisers"))
        {
        holder.foodIcon.setImageResource(R.drawable.appetiser);
        }
        else
            if(fl.bundleCategory.equals("Main Courses"))
            {
                holder.foodIcon.setImageResource(R.drawable.main_course);
            }
            else
                if(fl.bundleCategory.equals("Sides"))
                {
                    holder.foodIcon.setImageResource(R.drawable.sides);
                }
                else
                    if(fl.bundleCategory.equals("Desserts"))
                    {
                        holder.foodIcon.setImageResource(R.drawable.desserts);
                    }
                    else
                        if(fl.bundleCategory.equals("Drinks"))
                        {
                            holder.foodIcon.setImageResource(R.drawable.drinks);
                        }
        holder.tvFoodName.setText(foodList.get(position).getMenuItem());
        holder.tvFoodDescription.setText(foodList.get(position).getDescription());
        holder.cbSelectFood.setChecked(checks.get(position));
        holder.tvQuantity.setText(String.valueOf(quantity.get(position)));      
        return row;     
    }

}

Suppose i select(check) two list items and then press addToOrder button it just prints the last seleccted item twice. 假设我选择(检查)两个列表项,然后按addToOrder按钮,它仅将最后选择的项目打印两次。 I dont know why its just overridding a first object in my List I think my logic is correct, but dont know why its not working?? 我不知道为什么它只是覆盖列表中的第一个对象,我认为我的逻辑是正确的,但不知道为什么它不起作用? Can any one please help 有人可以帮忙吗

You should make a method in your adapter which lets your update the current arraylist or add/remove the item you pass. 您应该在适配器中创建一个方法,该方法可让您更新当前的数组列表或添加/删除传递的项目。 But I can't see how you implemented your adapter which probably is the most important code... 但是我看不到您是如何实现适配器的,这可能是最重要的代码...

You need something like this, inside your adapter (this is to update a full list): 您需要在适配器内部添加以下内容(以更新完整列表):

public void updateListArray(ArrayList<Item> list) {
    this.clear();
    for(Item item : list) {
        this.add(item);
    }
    notifyDataSetChanged();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM