Reloading the List

There is one more detail to take care of. Run CriminalIntent, press a list item, and then modify that Crime’s details. These changes are saved to the model, but when you return to the list, the RecyclerView is unchanged.

The RecyclerView’s Adapter needs to be informed that the data has changed (or may have changed) so that it can refetch the data and reload the list. You can work with the ActivityManager’s back stack to reload the list at the right moment.

When CrimeListFragment starts an instance of CrimeActivity, the CrimeActivity is put on top of the stack. This pauses and stops the instance of CrimeListActivity that was initially on top.

When the user presses the Back button to return to the list, the CrimeActivity is popped off the stack and destroyed. At that point, the CrimeListActivity is started and resumed (Figure 10.4).

Figure 10.4  CriminalIntent’s back stack

Illustration shows Swiping to page through crimes.

When the CrimeListActivity is resumed, it receives a call to onResume() from the OS. When CrimeListActivity receives this call, its FragmentManager calls onResume() on the fragments that the activity is currently hosting. In this case, the only fragment is CrimeListFragment.

In CrimeListFragment, override onResume() and trigger a call to updateUI() to reload the list. Modify the updateUI() method to call notifyDataSetChanged() if the CrimeAdapter is already set up.

Listing 10.9  Reloading the list in onResume() (CrimeListFragment.java)

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    ...
}

@Override
public void onResume() {
    super.onResume();
    updateUI();
}

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

Why override onResume() to update the RecyclerView and not onStart()? You cannot assume that your activity will be stopped when another activity is in front of it. If the other activity is transparent, your activity may just be paused. If your activity is paused and your update code is in onStart(), then the list will not be reloaded. In general, onResume() is the safest place to take action to update a fragment’s view.

Run CriminalIntent. Select a crime and change its details. When you return to the list, you will immediately see your changes.

You have made progress with CriminalIntent in the last two chapters. Let’s take a look at an updated object diagram (Figure 10.5).

Figure 10.5  Updated object diagram for CriminalIntent

Figure shows object diagram for CriminalIntent.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.70.132