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 = 
 getPreferences(Activity.MODE_PRIVATE);
// Retrieve an editor to modify the shared preferences.
SharedPreferences.Editor editor = activityPreferences.edit();
// Retrieve the View
TextView myTextView = (TextView)findViewById(R.id.myTextView);
// Store new primitive types in the shared preferences object.
editor.putString(“currentTextValue”, 
 myTextView.getText().toString());
// Commit changes.
editor.apply();

Leave a Comment