概况
Android 中的数据存储主要有两种方式:
- 一种时存储简单的数据:SharedPreferences
- 一种数据库存储:SQLite
比较 | SharedPreferences | SQLite |
---|---|---|
存在 | onPause() | 数据库引擎 |
大小 | 简易数据 | 数据库管理 |
形式 | Key- Value | SQL |
文件类型 | 文本形式 | |
特点 | 孤立数据 文本形式 持久化存储 | 只是一个文件,可使用文件权限来管理数据库 |
适用 | 记住密码 set 设置 | 大型数据 |
数据格式 | XML格式 | 结构化数据 |

效果演示 — 设置 “背景色”

SharedPreferences 操作要点
设置shared preferences
- 添加成员变量,hold 住 shared preferences file 只有引用SharedPreferences object.
private SharedPreferences mPreferences;
private String sharedPrefFile =
"com.example.a1104.android.hellosharedprefs";
- 启动时,初始化
In the onCreate() method, initialize the shared preferences.
mPreferences = getSharedPreferences(sharedPrefFile, MODE_PRIVATE);
- 由于它是在
onPause()
中的,需要重写onPause()
@Override
protected void onPause(){
super.onPause();
// 在sharePreferences 中获得 editor 操作
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.putInt(COUNT_KEY, mCount); // 设置mCount ,mColor 的keys
preferencesEditor.putInt(COLOR_KEY, mColor); // 如果是文本时putString()
preferencesEditor.apply(); // save
//The apply() method saves the preferences asynchronously, off of the UI thread
}
删除掉具有相同数据的onSaveInstanceState() 方法
在onCreate()
中设置
mCount = mPreferences.getInt(COUNT_KEY, 0);
//the getInt() method takes two arguments: one for the key, and the other for the default value if the key cannot be found . 0是默认值
mShowCountTextView.setText(String.format("%s", mCount)); //更新
mColor = mPreferences.getInt(COLOR_KEY, mColor);
mShowCountTextView.setBackgroundColor(mColor);
完整的代码:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initialize views, color, preferences
mShowCountTextView = (TextView) findViewById(R.id.count_textview);
mColor = ContextCompat.getColor(this, R.color.default_background);
mPreferences = getSharedPreferences(
mSharedPrefFile, MODE_PRIVATE);
// Restore preferences
mCount = mPreferences.getInt(COUNT_KEY, 0);
mShowCountTextView.setText(String.format("%s", mCount));
mColor = mPreferences.getInt(COLOR_KEY, mColor);
mShowCountTextView.setBackgroundColor(mColor);
}
此时运行,就可以实现设置操作了
设置 reset()
- 在reset()方法中引入
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
- 清楚掉之前的设置值
preferencesEditor.clear();
- 在执行新的
preferencesEditor.apply();
完整代码:
public void reset(View view) {
// Reset count
mCount = 0;
mShowCountTextView.setText(String.format("%s", mCount));
// Reset color
mColor = ContextCompat.getColor(this, R.color.default_background);
mShowCountTextView.setBackgroundColor(mColor);
// Clear preferences
SharedPreferences.Editor preferencesEditor = mPreferences.edit();
preferencesEditor.clear();
preferencesEditor.apply();
}