Android Programming The Big Nerd Ranch Guide by Bill Phillips, Chris Stewart, Kristin Marsicano (z-lib.org)

(gtxtreme123) #1

Chapter 14  SQLite Databases


Refreshing model data


You are not quite done. Your crimes are persistently stored to the database, but the persistent data is
not read back in. So if you press the Back button after editing your new Crime, it will not show up in
CrimeListActivity.


This is because CrimeLab now works a little differently. Before, there was only one List
and one object for each Crime: the one in the List. That was because mCrimes was the only
authority for which Crimes your app knew about.


Things have changed now. mCrimes is gone. So the List returned by getCrimes() is a
snapshot of the Crimes at one point in time. To refresh CrimeListActivity, you need to update that
snapshot.


Most of the moving pieces to do this are already in place. CrimeListActivity already calls
updateUI() to refresh other parts of its interface. All you need to do is have it refresh its view of
CrimeLab, too.


First, add a setCrimes(List) method to CrimeAdapter to swap out the crimes it displays.


Listing 14.20  Adding setCrimes(List) (CrimeListFragment.java)


private class CrimeAdapter extends RecyclerView.Adapter {
...
@Override
public int getItemCount() {
return mCrimes.size();
}


public void setCrimes(List crimes) {
mCrimes = crimes;
}
}


Then call setCrimes(List) in updateUI().


Listing 14.21  Calling setCrimes(List<>) (CrimeListFragment.java)


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


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


updateSubtitle();
}


Now everything should work correctly. Run CriminalIntent and verify that you can add a crime, press
the Back button, and see that crime in CrimeListActivity.

Free download pdf