SharedPreferences是一种轻型的数据存储方式,基于XML文件存储key-value pairs键值对数据,通常用来存储一些简单的配置信息。SharedPreferences对象本身只能获取数据而不支持存储和修改,存储修改是通过Editor对象实现。每一个 SharedPreferences 文件都是由framework管理的并且可以是私有或者可共享的。
数据存储
新建一个Android项目,在MainActivity的onCreate方法中,调用getSharedPreferences方法,需要注意的是,如果已经存在文件则不会新建,如果键值对不存在则会继续添加到里面,如果存在名字相同,值不同则会覆盖原有的值。
|
1
2
3
4
5
6
7
|
Context context=MainActivity.this;
SharedPreferences shared=context.getSharedPreferences("Test", MODE_PRIVATE);
Editor editor=shared.edit();editor.putString("Name", "FlyElephant");
editor.putInt("Age", 24);
editor.putBoolean("IsMarried", false);
editor.commit(); |
存储完之后这个时候之后就发现,文件夹下多了一个Test.xml,全路径应该是data/data/com.example.preference/shared_prefs/Test.xml
导出之后发现xml中内容为:
|
1
2
3
4
5
6
|
<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map><string name="Name">FlyElephant</string>
<int name="Age" value="24" />
<boolean name="IsMarried" value="false" />
</map> |
显示数据
设置一个按钮点击事件loadData
|
1
2
3
4
5
6
7
8
|
public void loadData(View view){
SharedPreferences shared=MainActivity.this.getSharedPreferences("Test", MODE_PRIVATE);
EditText editText=(EditText) findViewById(R.id.edit_sharedName);
editText.setText(shared.getString("Name", ""));
EditText editAge=(EditText) findViewById(R.id.edit_sharedAge);
String ageString=String.valueOf(shared.getInt("Age", 0));
editAge.setText(ageString);
}
|
数据显示结果:
删除节点
点击第二个按钮,执行的事件:
|
1
2
3
4
5
6
7
|
public void deleteNode(View view) {
SharedPreferences shared=MainActivity.this.getSharedPreferences("Test", MODE_PRIVATE);
Editor editor=shared.edit();
editor.remove("Age");
editor.commit();
Toast.makeText(MainActivity.this, "删除成功",Toast.LENGTH_SHORT).show();
}
|
效果如下:
删除文件
根据路径,调用一下File就直接删除了这个文件:
|
1
2
3
4
5
6
7
8
9
|
public void deleteFile(View view){
String pathString="/data/data/"+getPackageName()+"/shared_prefs";
File file=new File(pathString,"Test.xml");
Log.i("com.example.preference",pathString);
if (file.exists()) {
file.delete();
}
Toast.makeText(MainActivity.this, "文件删除成功",Toast.LENGTH_SHORT).show();
} |
本文转自Fly_Elephant博客园博客,原文链接:http://www.cnblogs.com/xiaofeixiang/p/4044683.html,如需转载请自行联系原作者