What if we didn't use an updateUI() method?


#1

This is our updateUI() method in Listing 10.9

private void updateUI() {
    CrimeLab crimeLab = CrimeLab.get(getActivity());
    List<Crime> crimes = crimeLab.getCrimes();

    if (mAdapter == null) {
        mAdapter = new CrimeAdapter(crimes);
        mCrimeRecyclerView.setAdapter(mAdapter);
    } else {
        mAdapter.notifyDataSetChanged();
    }
}

It seems like an odd way to implement things. Would there be a downside to just putting this part

        CrimeLab crimeLab = CrimeLab.get(getActivity());
        List<Crime> crimes = crimeLab.getCrimes();
        mAdapter = new CrimeAdapter(crimes);
        mCrimeRecyclerView.setAdapter(mAdapter);

in the onCreateView() method, and then

        mAdapter.notifyDataSetChanged();

in our onResume() method?
Combining them, getting a reference to a variable that may or may not be needed, and using an if-else statement feels like unnecessary complication to me, but I am also inexperienced so there’s probably something I’m not aware of that makes this the best implementation. If that’s the case, I’d like to learn!

Thanks!


#2

I can’t remember the reason why we structured the code that way. You are correct that you could refactor it in the way you did and everything should work correctly.

I may be forgetting something but I can’t think of any reason why your solution wouldn’t work with the rest of the updates to that app. In a real project, I’d probably have similar code to what you proposed.


#3

In the following chapters, the updateUI() will be reused when you want to create a new Crime in the CrimeListFragment.

During that time, the list of the crimes will be updated and the adapter’s data set will be changed as well without the calling of onCreateView() and onResume().

So, use an updateUI() method will keep the code be more reusable.