SharedPreferences是一种轻量级的数据存储方式,使用key-value键值对来将数据存储到xml文件中。
基本使用
在任何情况下使用SharedPreferences,首先要通过getSharedPreferences方法获取到SharedPreferences()对象,传入的第一个参数为文件名称,第二个参数指定访问应用程序私有文件的权限,如果已经存在该文件则打开,否则新建
SharedPreferences data=getSharedPreferences("data",0);
//SharedPreferences example=getActivity.getSharedPreferences("example",0); // 在Fragment中使用
存数据
SharedPreferences.Editor editor=data.edit();
editor.putString("name","demo");
editor.putString("password","123456");
editor.commit();//提交保存
读数据
String name=data.getString("name","default");
String password=data.getString("password","default");
删除数据
SharedPreferences.Editor editor=data.edit();
editor.remove("name");
editor.commit();
清空数据
SharedPreferences.Editor editor=data.edit();
editor.clear();
editor.commit();