20.08.2016 Views

Professional Android 4 Application Development

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

242 x CHAPTER 7 FILES, SAVING STATE,AND PREFERENCES<br />

}<br />

startActivityForResult(i, SHOW_PREFERENCES);<br />

return true;<br />

}<br />

}<br />

return false;<br />

All the code snippets in this example are part of the Chapter 7 Earthquake Part 2<br />

project, available for download at www.wrox.com.<br />

PERSISTING THE APPLICATION INSTANCE STATE<br />

To save Activity instance variables, <strong>Android</strong> offers two specialized variations of Shared Preferences.<br />

The first uses a Shared Preference named specifically for your Activity, whereas the other relies on a<br />

series of lifecycle event handlers.<br />

Saving Activity State Using Shared Preferences<br />

If you want to save Activity information that doesn’t need to be shared with other components<br />

(e.g., class instance variables), you can call Activity.getPreferences()without specifying a<br />

Shared Preferences name. This returns a Shared Preference using the calling Activity’s class name as<br />

the Shared Preference name.<br />

// Create or retrieve the activity preference object.<br />

SharedPreferences activityPreferences =<br />

getPreferences(Activity.MODE_PRIVATE);<br />

// Retrieve an editor to modify the shared preferences.<br />

SharedPreferences.Editor editor = activityPreferences.edit();<br />

// Retrieve the View<br />

TextView myTextView = (TextView)findViewById(R.id.myTextView);<br />

// Store new primitive types in the shared preferences object.<br />

editor.putString(“currentTextValue”,<br />

myTextView.getText().toString());<br />

// Commit changes.<br />

editor.apply();<br />

Saving and Restoring Activity Instance State Using the<br />

Lifecycle Handlers<br />

Activities offer the onSaveInstanceState handler to persist data associated with UI state across<br />

sessions. It’s designed specifically to persist UI state should an Activity be terminated by the run<br />

time, either in an effort to free resources for foreground applications or to accommodate restarts<br />

caused by hardware configuration changes.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!