Android Programming The Big Nerd Ranch Guide, 3rd Edition

(Brent) #1

Chapter 12  Dialogs


242

Make the method private and name it updateDate. Click OK and Android Studio will tell you that
it has found one other place where this line of code was used. Click Yes to allow Android Studio
to update the other reference, then verify that your code is now extracted to a single updateDate()
method, as shown in Listing 12.13.


Listing 12.13  Cleaning up with updateDate() (CrimeFragment.java)


public class CrimeFragment extends Fragment {
...
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, container, false);
...
mDateButton = (Button) v.findViewById(R.id.crime_date);
updateDate();
...
}


@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK) {
return;
}


if (requestCode == REQUEST_DATE) {
Date date = (Date) data
.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDate();
}
}


private void updateDate() {
mDateButton.setText(mCrime.getDate().toString());
}
}


Now the circle is complete. The dates must flow. He who controls the dates controls time itself.
Run CriminalIntent to ensure that you can, in fact, control the dates. Change the date of a Crime and
confirm that the new date appears in CrimeFragment’s view. Then return to the list of crimes and check
the Crime’s date to ensure that the model layer was updated.

Free download pdf