Why does clearing the arraylist for a RecyclerAdapter cause the adapter to update?

I have a button which clears the Arraylist that a RecyclerAdapter is using, but this causes the List to update even though I don’t call .notifyDataSetChanged()

 @OnClick(R.id.btn_search)
    void onBtnSearchClick() {
        String name = String.valueOf(searchView.getQuery()).trim();
        if(name.equals("")){
            return;
        }

        btnSearch.setClickable(false);
        tvNoResults.setVisibility(View.GONE);
        
        centerProgressBar.setVisibility(View.VISIBLE);

        listUsers.clear();    //An ArrayList

        Log.d(TAG, "onBtnSearchClick: " + listUsers.size());
        
    }

Is this the expected behavior?

Answer

This is not related to RecyclerView at all . Its all about the Object reference . Consider the code block below

ArrayList<String> list=new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    binding.recylerView.setAdapter(new MyAdapter(list));    
}

In this case if i use same ArrayList for showing data in MyAdapter i.e list . then it will be holding the same reference . and if any point of time i make any modification on list this will reflect in MyAdapters's list too because they Are pointing to same reference regardless of calling notifyDataSetChanged() .

this is why you have notify the adapter for any changes you made otherwise you will see weird behavior when you access the data item for any position and some times exception too like java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid item position.

Leave a Reply

Your email address will not be published. Required fields are marked *