Home > OS >  Android ArrayList "B" clears when I call clear on ArrayList "A"
Android ArrayList "B" clears when I call clear on ArrayList "A"

Time:12-10

I am using the second answer from this question How to filter a RecyclerView with a SearchView. I only changed the names of the ArrayLists so the code is the same. Problem is when I clear the main ArrayList, for some reason the secondary list also clears. Unless I am missing something obvious this shouldn't be happening. The code is attached below;

This is my constructor;

public CustomFoodAdapter(Context context, ArrayList<Foods> foodsArray) {
        this.context = context;
        this.foods = foodsArray;
        this.foodsCopy = foodsArray;
    } 

And this is the method I call;

public void filter(String text) {

        System.out.println("Foods copy: " foodsCopy.size()); // Size is 54
        foods.clear();
        System.out.println("2 Foods copy: " foodsCopy.size()); // Size is 0 (???)
        if(text.isEmpty()){
            foods.addAll(foodsCopy);
        } else{
            text = text.toLowerCase();
            System.out.println("Length is: " foodsCopy.size());
            for(Foods item: foodsCopy){
                System.out.println("Food name: " item.foodName);
                if(item.getFoodName().toLowerCase().contains(text)){
                    foods.add(item);
                }
            }
        }
        notifyDataSetChanged();
    }

CodePudding user response:

This is because you are copying the list in memory reference and not the content itself.

So in the CustomFoodAdapter constructor you would need to create a new array list with the foodsArray content in it.

It would be something like this:

public CustomFoodAdapter(Context context, ArrayList<Foods> foodsArray) {
        this.context = context;
        this.foods = new ArrayList<>(foodsArray);
        this.foodsCopy = new ArrayList<>(foodsArray);
}
  • Related