saveCrimes() called for each Crime - Move onPause()


Having CrimeFragment save the Crimes to file in the onPause() method is causing the app to do this for each Crime in the list. Moving this to CrimePagerActivity causes it to only get called twice when you go back to the list and every time you swipe between Crimes in the pager view. For now, we can forget about only saving when something was actually changed or added to a Crime.

@Override public void onPause() { super.onPause(); CrimeLab.get(this).saveCrimes(); Log.d(TAG, "onPause()"); }

The onPause() in both classes is also called when the CrimeCameraFragment is displayed to take a picture.

So, will moving it to CrimePagerActivity cause the app to possibly not save when it should? It seems to get called whenever you leave the CrimeFragment view (going back to the list or forward to another screen or app)?

Could having the saveCrimes() get called for each Crime cause a problem if we haven’t made it thread safe? The emulator is crashing on me a lot since doing chapter 20. I get a Windows pop-up saying something like “emulator-app.exe has stopped”, and when this happens there is nothing in LogCat to help. Is it possibly related to what I said in the Chapter 20 thread about constantly resizing the original image instead of creating a scaled version to use in the app? I overloaded onLowMemory() in CrimeFragment to see, but haven’t had it hit this yet.



First, I don’t think that thread safety is causing issues here. onPause() is always called on the main thread, so it doesn’t matter whether it’s thread safe or not. So I don’t think that you’re experiencing any performance issues that are related to saving the crime list multiple times.

Now, as to your fix. Yes, it will work perfectly, but it breaks the encapsulation of CrimeFragment. With the saving done in the activity, there’s a silent contract - if you host CrimeFragment, then you must override onPause() and saveCrimes() to get appropriate behavior. The better fix would be to save only the data for the specific crime CrimeFragment is looking at.

Memory is the more likely culprit for the issue you’re facing, but it’s impossible to say for sure. That’s not the most informative crash in the world. :frowning: