I would do it differently.
To check the list, you only need to do something like:
for (int i = 0; i < numItems; i++) { onData(anything()) .inAdapterView(withId(R.id.listViewId)).atPosition(i) .check(matches(isDisplayed())); }
And, before, to get the numItems variable you just need to access your list adapter through an ActivityTestRule:
int numItems = ((ListView) mActivityRule.getActivity().findViewById(R.id.listViewId)).getAdapter().getCount();
Or if its inside a fragment:
int numItems = ((ListView) mActivityRule.getActivity().getSupportFragmentManager().findFragmentById(R.id.fragmentId).getView().findViewById(R.id.listViewId)).getAdapter().getCount();
Despite the fact that I understand your code, I think it is easier to understand. The only confusing part is the way to access the adapter. But you can create other intermediate variables to make it more readable or create a function to get this number if you want.
source share