Android Arraylist Baseadapter 按钮点击 Create new Arraylist with no dulicacy

Android Arraylist Baseadapter button click Create new Arraylist with no duplicacy

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

    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);它给了我 arrayindexoutofbound 异常。

谢谢

你面对着ArrayIndexOutOfBoundsException

Thrown to indicate that an array has been accessed with an illegal index. The index is either negative or greater than or equal to the size of the array.

For Duplicate issue 你应该使用HashSet

Main difference between ArrayList and HashSet is that ArrayList allow duplicates while HashSet doesn't allow duplicates.

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

尝试下面的代码和这个 Gradle 在你的 build.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();

createView 方法的另一个片段添加以下代码

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

        }
}

这是避免重复数据的好方法

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

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