How to use SharedPreferences?

If you have a relatively small collection of key-values that you'd like to save, you should use the SharedPreferences.

/* Strore data in sharedPreferences */ 
SharedPreferences sharedPreferences  = getSharedPreferences("SAVED_USER_DATA", MODE_PRIVATE);
                                SharedPreferences.Editor editor = sharedPreferences.edit();
                                editor.putString(WebService.USER_ID, user_id);
                                editor.putString(WebService.USER_FIRSTNAME, firstname);
                                editor.putString(WebService.USER_LASTNAME, lastname);
                                editor.putString(WebService.USER_EMAIL, email);
                                editor.putString(WebService.USER_PHONE_NUMBER, phone);
                                editor.apply();

/* Retrieve data from sharedPreferences */
sharedPreferences = getSharedPreferences("SAVED_USER_DATA", MODE_PRIVATE);
        userID = sharedPreferences.getString(WebService.USER_ID, null);
        email = sharedPreferences.getString(WebService.USER_EMAIL, null);
        phone_number = sharedPreferences.getString(WebService.USER_PHONE_NUMBER, null);
        name = sharedPreferences.getString(WebService.USER_FIRSTNAME, null) + " " +
                sharedPreferences.getString(WebService.USER_LASTNAME, null);

/* Clear sharedPreferences */
sharedPreferences.edit().clear().commit();

Comments