Saving Activity State Using Shared Preferences in Android

If you want to save Activity information that doesn’t need to be shared with other components (e.g., class instance variables), you can call Activity.getPreferences() without specifying a Shared Preferences name. This returns a Shared Preference using the calling Activity’s class name as the Shared Preference name

// Create or retrieve the activity preference object.
SharedPreferences activityPreferences = 
// Retrieve an editor to modify the shared preferences.
SharedPreferences.Editor editor = activityPreferences.edit();
// Retrieve the View
TextView myTextView = (TextView)findViewById(;
// Store new primitive types in the shared preferences object.
// Commit changes.

Leave a Comment