I was going through the source code of ListView and stumbled upon the setAdapter method which goes somewhat like this:-
public void setAdapter(ListAdapter adapter) {
if (mAdapter != null && mDataSetObserver != null) {
mAdapter.unregisterDataSetObserver(mDataSetObserver);
}
resetList();
mRecycler.clear();
if (mHeaderViewInfos.size() > 0|| mFooterViewInfos.size() > 0) {
mAdapter = wrapHeaderListAdapterInternal(mHeaderViewInfos, mFooterViewInfos, adapter);
} else {
mAdapter = adapter;
}
mOldSelectedPosition = INVALID_POSITION;
mOldSelectedRowId = INVALID_ROW_ID;
// AbsListView#setAdapter will update choice mode states.
super.setAdapter(adapter);
if (mAdapter != null) {
mAreAllItemsSelectable = mAdapter.areAllItemsEnabled();
mOldItemCount = mItemCount;
mItemCount = mAdapter.getCount(); //DOUBT!!!!!
checkFocus();
If we see the second line from bottom, we will see that we are setting the mItemCount to the size of Array passed to the adapter at the time of creation of the adapter object.
My doubt is, let suppose we initialised the Array with 5 elements and also created the Adapter Object in the next line, and then called setAdapter on this object. On doing so, our mItemCount will be set to 5.
Now, let suppose we added 5 more elements, so our Array became of size 10 but since we won't call the setAdapter(..) again, our mItemCount remains 5 and on running the app we should just see 5 top elements of the array.
But I am able to see that 10 elements have been added to the listview. Where is the mItemCount getting updated again?
MainActivity.java looks like below:
public class MainActivity extends AppCompatActivity {
private ArrayList<Integer> arr;
private ListView listView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
arr = new ArrayList<Integer>();
setContentView(R.layout.activity_main);
for(int i = 0; i < 5; i++){
arr.add(i);
}
ArrayAdapter adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_list_item_1, arr);
listView = findViewById(R.id.listView);
listView.setAdapter(adapter);
for(int i = 5; i < 10; i++)
arr.add(i);
}
}
Edit 1: Attaching the MainActivity.java which I am using which shows inconsistency with my expectation.