3rd challenge and static ArrayList


This is probably a beginner’s question… I handled the 3rd challenge by creating an ArrayList that stores integers. I add mCurrentIndex for each question the user cheats on and check if a question’s mCurrentIndex is in the ArrayList to show the JudgmentToast.

Without really thinking about it, I declared the ArrayList as a static, like so:

	private static ArrayList<Integer> mCheatList = new ArrayList<Integer>();

I then added code to save the ArrayList when the device rotates, like so:

Added to saveInstanceState:

		savedInstanceState.putIntegerArrayList("mCheatList", mCheatList);

Added to onCreate, in the savedInstanceState condition:

			mCheatList = savedInstanceState.getIntegerArrayList("mCheatList");
			if (mCheatList.size() > 0) {
				for (int mNumber : mCheatList) {
				Log.d(TAG, Integer.toString(mCheatList.get(mNumber)));

There are two things I don’t understand:

  1. The savedInstanceState code appears to be redundant, as the ArrayList survives device rotation without it. It seems that this follows from declaring the ArrayList as a static, is that correct? Do static variables always survive rotation?

  2. Why is the Log.d codeline crashing the app?




1- You’re right that statics appear to solve the problem. Using them in this way, though, is a huge red flag, and very bad practice.

The reason they’re such a bad idea is exactly why they seem like a good idea; they appear to work well. They don’t work in all circumstances, though. If your process is shut down, your saved instance state will be preserved. All your statics, however, will go away.

Of course, we do use static references elsewhere in the app. CrimeLab is really just a fancy static reference. CrimeLab is self contained, though, and is capable of restoring its data should the process be shut down.

2- It’s hard to say without seeing a stack trace, but my guess would be that mCheatList.get(mNumber) is return a null reference.