7a. Android: Shared Preferences: saving and fetching persistent data

In this tutorial you will learn how to save and retrieve user preferences.

Step 1: Create a new app (module)



  • Blank Activity
  • Activity Name: MainActivity
  • Layout Name: activity_main




Step 2: build the app


If you receive the following error, make sure "Project Structure" has the right SDK version settings.

Failure [INSTALL_FAILED_OLDER_SDK]



Step 3: create basic UI

  • TextView "My Important Info:"
  • EditText  infoEditText
  • Button saveButton


Enter some super important stuff (type in text). 

Step 4: KILL the app, restart

when you re-open the app the text is gone :(

Step 5: Declare your UI components in MainActivity


public class MainActivity extends ActionBarActivity {

   private EditText infoEditText;
   private Button saveButton;


Step 6: Wire your UI components in onCreate()

  infoEditText = (EditText) findViewById(R.id.infoEditText);
      saveButton = (Button) findViewById(R.id.saveButton);
      saveButton.setOnClickListener(saveListener);


We will use Log, so define the TAG in MainActivity as class member.

 private static final String TAG = MainActivity.class.getSimpleName();

Step 7: Define a name for our key-value


   /**
    * We will be using this constant as a "key" i.e. name of our key-value pair
    */
   static final String PREFERENCE_KEY_INFO = "MY_INFO";


Step 8: Write your Listener


 /**
    * This listener class can be used for any View e.g. Button
    */
   View.OnClickListener saveListener = new View.OnClickListener() {
      public void onClick(View v) {
         Log.i(TAG, "onClick detected in view " + v.getClass().getSimpleName());
         String key = PREFERENCE_KEY_INFO;
         String value = infoEditText.getText().toString();
         if (value.equals("")) {
            Log.w(TAG, "You did not provide any text! Saving anyway.");
         }
         preferences.save(key, value);
      }
   };

Step 9: Create SharedPreferencesHelper


package com.chicagoandroid.cit299.userpreferences;
import android.content.Context;
import android.content.SharedPreferences;
import android.util.Log;
/**
 * This helper class will abstract the use of Shared Preferences and will make them very reusable.
 */
public class SharedPreferencesHelper {
   private SharedPreferences preferences;
   private Context parentContext;
   private String preferencesName;
   private static String TAG;
   /**
    * This is a constructor that will set up context of the preferences.
    * @param context - the calling Activity context.
    * @param preferencesName - desired preferences store name.
    */
   public SharedPreferencesHelper(Context context, String preferencesName) {
      parentContext = context;
      preferencesName = preferencesName;
      TAG = parentContext.getClass().getSimpleName() + "." + SharedPreferencesHelper.class.getSimpleName();
   }

Step 10: add save() to SharedPreferencesHelper

  /**
    * This method will save User Preferences
    *
    * @param key   - the unique name of the preference
    * @param value - the String value to be saved
    */
   public void save(String key, String value) {
      if (preferences == null) {
         preferences = parentContext.getSharedPreferences(preferencesName, Context.MODE_APPEND);
         Log.i(TAG, "Creating shared preferences");
      }
      String message = "saveUserPreferences() for " + preferencesName + "  key: " + key + ", value: " + value;
      Log.d(TAG, message);
      SharedPreferences.Editor editor = preferences.edit();
      editor.putString(key, value);
      editor.commit();

   }


Step 11: add fetch()  to SharedPreferencesHelper


  /**
    * Method used to restore Shared Preference
    * @param key
    * @param defaultValue`
    * @return
    */
   public String fetch(String key, String defaultValue) {
      if (preferences == null) preferences = parentContext.getSharedPreferences(preferencesName, Context.MODE_APPEND);
      String savedText = preferences.getString(key, defaultValue);
      Log.i("restoreUserPreferences() for " + preferencesName, " key: " + key + " value: " + savedText);
      return savedText;
   }


Step 12: Define the rest of Activity class variables


public class MainActivity extends ActionBarActivity {
   private EditText infoEditText;
   private Button saveButton;
   /**
    * We will be using this constant as a "key" i.e. name of our key-value pair
    */
   static final String PREFERENCE_KEY_INFO = "MY_INFO";
   SharedPreferencesHelper preferences;
   private static final String MAIN_PREFERENCES = MainActivity.class.getCanonicalName();   private static final String TAG = MainActivity.class.getSimpleName();





Step 13: update onCreate() to fetch any saved preferences



   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      preferences = new SharedPreferencesHelper(this, MAIN_PREFERENCES);
      setContentView(R.layout.activity_main);
      infoEditText = (EditText) findViewById(R.id.infoEditText);
      saveButton = (Button) findViewById(R.id.saveButton);
      saveButton.setOnClickListener(saveListener);
      infoEditText.setText(preferences.fetch(PREFERENCE_KEY_INFO, "my default value"));
   }

Step 14: restart and test the app

The first time you open the app the default value should be in the EditText.


Step 15: Implement security


read more: 
https://github.com/sveinungkb/encrypted-userprefs/blob/master/src/SecurePreferences.java

No comments:

Post a Comment