欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

android开发基础教程—SharedPreferences读写

程序员文章站 2023-12-02 20:02:28
复制代码 代码如下: public class mainactivity extends activity { @override protected void oncre...
复制代码 代码如下:

public class mainactivity extends activity {
@override
protected void oncreate(bundle savedinstancestate) {
super.oncreate(savedinstancestate);
setcontentview(r.layout.activity_main);
}
public void onclick(view v) {
switch (v.getid()) {
case r.id.button1:
sharedpreferences sp = this.getsharedpreferences("myxml", context.mode_private);
editor editor = sp.edit();
editor.putstring("name", "nanguabing");
editor.putint("age", 20);
//持久化操作到存储设备
editor.commit();
toast.maketext(this, "写入sp完成", 1).show();
break;
case r.id.button2:
sharedpreferences sp1 = this.getsharedpreferences("myxml", context.mode_private);
string name = sp1.getstring("name", "nobody");
int age = sp1.getint("age", 0);
toast.maketext(this, "name=" + name + ",age=" + age, 1).show();
break;
default:
break;
}
}
@override
public boolean oncreateoptionsmenu(menu menu) {
// inflate the menu; this adds items to the action bar if it is present.
getmenuinflater().inflate(r.menu.activity_main, menu);
return true;
}
}

文件格式:
复制代码 代码如下:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="name">nanguabing</string>
<int name="age" value="20" />
</map>