Lifecycle methods called multiple times


#1

I noticed that lifecycle methods are called two or three times in CrimeFragment. This is what happens when I add a new Crime and then navigate back with the back button or action bar (I only logged resume, start, pause, stop and destroy):

05-09 12:57:52.334: D/CrimeFragment(1297): OnStart() called in CrimeFragment 05-09 12:57:52.421: D/CrimeFragment(1297): OnResume() called in CrimeFragment 05-09 12:57:52.791: D/CrimeFragment(1297): OnStart() called in CrimeFragment 05-09 12:57:52.851: D/CrimeFragment(1297): OnResume() called in CrimeFragment 05-09 12:57:57.593: D/CrimeFragment(1297): OnPause() called in CrimeFragment 05-09 12:57:57.593: D/CrimeFragment(1297): OnPause() called in CrimeFragment 05-09 12:57:59.151: D/CrimeFragment(1297): OnStop() called in CrimeFragment 05-09 12:57:59.151: D/CrimeFragment(1297): OnStop() called in CrimeFragment 05-09 12:57:59.171: D/CrimeFragment(1297): OnDestroy() called in CrimeFragment 05-09 12:57:59.191: D/CrimeFragment(1297): OnDestroy() called in CrimeFragment

I get this in the emulator, on a real device, with my own code and with the code from the solutions zip file.

What is the reason for this?

ps: really enjoy working through the book


#2

Today I’ve discovered it too (the saveCrimes method is called twice or three times in the example from Chapter 17).
It seems that the reason for that is the ViewPager, that loads the neighbour fragments, so when you leave CrimePagerActivity all created fragments are destroyed (2 fragments if you look a the first or the last one crime, or 3 fragments when you look at all the others).

I’ve added the following method to CrimeFragment to check which fragments are paused

	@Override
	public void onPause() {
		super.onPause();
		CrimeLab.get(getActivity()).saveCrimes();
		Log.d("CrimeFragment", mCrime.getTitle());
	}

#3

Marcin is correct - if the ViewPager is implemented, then 2-3 fragments will be loaded into the Running state as soon as you enter the activity.