Android Arraylist Baseadapter 按钮单击创建新 Arraylist,没有重复



我有一个自定义的列表视图基本适配器,其中我们在单击添加购物车按钮时在每行中添加购物车和按钮,它调用接口函数

    HeadingRowItem headingRowItem = (HeadingRowItem)rowItems.get(pos);
    addRowItem= new AddRowItem(headingRowItem.getTitle(),headingRowItem.getQty(),headingRowItem.getTotalqty(),headingRowItem.getPrices(),headingRowItem.getTotalprice());
    Log.d("myvalueb",""+data.size());
    data.add(addRowItem);

它工作正常,但它会产生重复,所以如果使用,如何避免重复data.set(pos,addRowItem(;它给了我数组索引出界异常。

谢谢

你面对 ArrayIndexOutOfBoundsException

抛出以指示已使用非法 指数。指数为负或大于或等于 数组的大小。

对于重复问题,您应该使用哈希集

ArrayList

和HashSet之间的主要区别在于ArrayList。 允许重复,而 HashSet 不允许重复。

  • 如果您尝试在 HashSet 中添加重复元素,则旧值将被覆盖。

这是避免重复数据的好解决方案

            for(int i=0;i<data.size();i++){//
                for(int j=i+1;j<data.size();j++){//
                    if(data.get(i).getTitle().equals(data.get(j).getTitle())){
                        data.remove(i);
                        j--;
                    }
                }
            }

在发送其他片段之前,它可以工作并在其他片段中为此数据创建一个新的适配器..谢谢大家..

在你的build.gradle中尝试下面的代码和这个Gradle compile 'com.google.code.gson:gson:2.7'compile 'org.jsoup:jsoup:1.10.2'

HashSet<AddRowItem> data = new HashSet<>();
data.add(addRowItem);
//add bundle
String details = new Gson().toJson(data);
Fragment homeFragment = new YourFragment();
FragmentTransaction homeTransaction = getFragmentManager().beginTransaction();
Bundle bundle = new Bundle();
bundle.putString("details", details);
homeFragment.setArguments(bundle);
homeTransaction.addToBackStack("YourFragment");
homeTransaction.replace(R.id.frame_container, homeFragment, "YourFragment");
homeTransaction.commit();

创建视图方法上的另一个片段添加以下代码

View onCreateView(){
        Bundle mBundle = getArguments();
        if (mBundle != null) {
            String details = mBundle.getString("details");
            HashSet<AddRowItem> data = new Gson().fromJson(details, HashSet.class);
        }
}

最新更新