Android学习笔记-SharedPreferences

支持多种类型的键值对存储。

1、将数据存储到SharedPreferences中

  • 有三种方法可以得到SharedPreferences对象

    1. Context类中的getSharedPreferces()方法
    2. Activity类中的getPreferenes()方法
    3. PreferencesManager类中的getDefaultSharedPreferces(context)方法
  • 写入数据

    1. Call edit() to get a SharedPreferences.Editor.
    2. Add values with methods such as putBoolean() and putString().
    3. Commit the new values with commit()
  • 读取数据, use SharedPreferences methods such as getBoolean() and getString().

Here is an example that saves a preference for silent keypress mode in a calculator:

public class Calc extends Activity {
    public static final String PREFS_NAME = "MyPrefsFile";

    @Override
    protected void onCreate(Bundle state){
       super.onCreate(state);
       . . .

       // Restore preferences
       SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
       boolean silent = settings.getBoolean("silentMode", false);
       setSilent(silent);
    }

    @Override
    protected void onStop(){
       super.onStop();

      // We need an Editor object to make preference changes.
      // All objects are from android.context.Context
      SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
      SharedPreferences.Editor editor = settings.edit();
      editor.putBoolean("silentMode", mSilentMode);

      // Commit the edits!
      editor.commit();
    }
}

2、记住密码功能

你可能感兴趣的:(android,数据存储)