Android屏幕旋转崩溃:井字棋应用OnSaveInstanceState方法异常排查求助
OnSaveInstanceState Hey there! Let’s figure out why your Tic-Tac-Toe app is crashing when you implement OnSaveInstanceState—I’ve dealt with similar headaches before, so let’s break down the most common culprits and fixes:
Common Causes & Fixes
1. You forgot to call the parent class method
This is the #1 mistake people make when overriding onSaveInstanceState. If you skip calling super.onSaveInstanceState(outState), you’re breaking the system’s default state-saving logic, which almost always leads to crashes.
Fix it like this:
@Override protected void onSaveInstanceState(Bundle outState) { // Save your custom game state first (e.g., current player, board data) outState.putInt("current_player", currentPlayer); outState.putSerializable("game_board", gameBoard); // Make sure gameBoard is serializable! // Critical: Call the parent class method to preserve system state super.onSaveInstanceState(outState); }
2. You’re trying to save non-serializable data
Bundle can only store primitive types, strings, and objects that implement Serializable or Parcelable. If your game board is a custom class that doesn’t implement either, or you’re trying to save a View object directly, the app will crash when serializing the Bundle.
Fix options:
- Convert your board data to a serializable type like a 2D
int[][]array instead of a custom class. - Make your custom board class implement
Serializable(addimplements Serializableto the class definition—no extra code needed for simple data classes).
3. Mismatched data types when restoring state
If you save an integer with putInt("player", 1) but try to retrieve it with getString("player"), or use a typo in the key name (e.g., "current_player" vs "currentPlayer"), you’ll get a runtime exception.
Fix it by verifying your restore logic:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (savedInstanceState != null) { // Match the data type and key exactly to what you saved currentPlayer = savedInstanceState.getInt("current_player", 1); // Default to player 1 if key is missing gameBoard = (int[][]) savedInstanceState.getSerializable("game_board"); } else { // Initialize a new game if no saved state exists initNewGame(); } }
4. Performing heavy or invalid operations in onSaveInstanceState
This method is meant only for saving lightweight state data. If you’re doing network calls, accessing already destroyed Views, or running long computations here, you’ll trigger crashes. Stick to saving simple values like player turns, board states, or scores.
Next Steps
If you’re still stuck, share the exact code of your onSaveInstanceState method and how you’re restoring the state—this will help pinpoint the exact issue. But odds are, one of the above fixes will get your app rotating without crashing!
内容的提问来源于stack exchange,提问作者Johnavan Thomas

