一,说明
- 存放单一小数据
- 存储数据类型:boolean,String,int,long,float
- 存储路径:/data/data/packageName/shared_prefs/yyy.xml
- 可以设置为当前应用私有
- 应用卸载时删除此数据
二,API
SharedPreferences相关
SharedPreferences context.getSharedPreferences(String name,int mode)
得到SharedPreferences对象
name:文件名(不带.xml)
mode:生成的文件模式(是否私有)Editor sp.edit()
得到Editor对象Xxx sp.getXxx(String name,Xxx defValue)
得到对应name的数据
Editor相关
Editor put(String name,Xxx value)
保存键值对(并未保存到文件中)Editor remove(String name)
移除键值对commit()
保存到文件中
三,测试源码
public class SPActivity extends Activity {
private EditText et_sp_key;
private EditText et_sp_value;
SharedPreferences sp;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sp);
et_sp_key = (EditText) findViewById(R.id.et_sp_key);
et_sp_value = (EditText) findViewById(R.id.et_sp_value);
sp = this.getSharedPreferences("mysp", MODE_PRIVATE);
}
public void onClickWrite(View v) {
Editor edit = sp.edit();
Editable keyEdit = et_sp_key.getText();
Editable valueEdit = et_sp_value.getText();
int value = Integer.parseInt(valueEdit.toString());
edit.putInt(keyEdit.toString(), value);
edit.commit();
}
public void onClickRead(View v) {
String key = et_sp_key.getText().toString();
String value = sp.getString(key, null);
if (value == null) {
Toast.makeText(this, "no such key!", 0).show();
} else {
et_sp_value.setText(value);
}
}
}