Game Development Reference
In-Depth Information
Overview of Persistent Data
You may have noticed that when you change the orientation of your Android device, the program
in our previous example restarts, and the two cubes' previous orientation and physics is lost. The
score and health items in the HUD are also lost and reset. In the Android system, you can use
SharedPreferences to save and load data to preserve the environment of your game.
To save the state of a class object, you can add in a function such as SaveState() , shown in
Listing 6-45, which:
Creates a SharedPreferences variable by calling getSharedPreferences() on
the context with the name of the record you want to save the data in
1.
Creates a SharedPreferences.Editor editor variable that is used to store the
data from the class object
2.
3.
Puts the data into the record by calling putXXXX(“name”, value) on the editor
variable to associate the value with the “name.” The XXXX is a data type
such as Float, Int, etc.
Saves the data by calling the commit() function on the editor
4.
Listing 6-45. Saving the State of an Object
void SaveState(String handle)
{
SharedPreferences settings = m_Context.getSharedPreferences(handle, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putFloat("x", m_Position.x);
// Commit the edits!
editor.commit();
}
To load the state of a class object, you could add a class such as LoadState() , shown in Listing 6-46,
which:
Creates a SharedPreferences variable by calling getSharedPreferences() on
the context with the name of the record you want to load the data from
1.
2.
Gets the data from the record by calling getXXXX(“name”, default value), in
which XXXX is the data type, such as Float, Int, etc. If “name” does not exist,
then the default value is returned.
Listing 6-46. Loading the State of an Object
void LoadState(String handle)
{
// Restore preferences
SharedPreferences settings = m_Context.getSharedPreferences(handle, 0);
float x = settings.getFloat("x", 0);
}
 
Search WWH ::




Custom Search