Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Android ArrayList "B" clears when I call clear on ArrayList "A"

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;

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading