5.5.3. Overridden Activity Method onStart

Overridden Activity lifecycle method onStart (Fig. 5.20) is called in two scenarios:

• When the app first executes, onStart is called after onCreate. We use onStart in this case to ensure that the quiz is configured correctly based on the app’s default preferences when the app is installed and executes for the first time or based on the user’s updated preferences when the app is launched subsequently.

• When the app is running in portrait orientation and the user opens the SettingsActivity, the MainActivity is paused while the SettingsActivity is displayed. When the user returns to the MainActivity, onStart is called again. We use onStart in this case to ensure that the quiz is reconfigured properly if the user made any preference changes.


61      // called after onCreate completes execution
62      @Override
63      protected void onStart()
64      {
65         super.onStart();
66
67         if (preferencesChanged)
68         {
69            // now that the default preferences have been set,
70            // initialize QuizFragment and start the quiz
71            QuizFragment quizFragment = (QuizFragment)                  
72               getFragmentManager().findFragmentById(R.id.quizFragment);
73            quizFragment.updateGuessRows(
74               PreferenceManager.getDefaultSharedPreferences(this));
75            quizFragment.updateRegions(
76               PreferenceManager.getDefaultSharedPreferences(this));
77            quizFragment.resetQuiz();
78            preferencesChanged = false;
79         }
80      } // end method onStart
81


Fig. 5.20 | MainActivity overridden Activity method onStart.

In both cases, if preferencesChanged is true, onStart calls QuizFragment’s updateGuessRows (Section 5.6.4) and updateRegions (Section 5.6.5) methods to reconfigure the quiz. To get a reference to the QuizFragment so we can call its methods, lines 71–72 use inherited Activity method getFragmentManager to get the FragmentManager, then call its findFragmentById method. Next, lines 73–76 call QuizFragment’s updateGuessRows and updateRegions methods, passing the app’s SharedPreferences object as an argument so those methods can load the current preferences. Line 77 resets the quiz.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset