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>
您可能感兴趣的文章:Android应用开发SharedPreferences存储数据的使用方法Android 清除SharedPreferences 产生的数据(实例代码)android中使用SharedPreferences进行数据存储的操作方法Android SharedPreferences的使用分析Android SharedPreferences实现记住密码和自动登录界面Android应用中使用SharedPreferences类存储数据的方法Android:利用SharedPreferences实现自动登录Android通过"记住密码"功能学习数据存储类SharedPreferences详解及实例Android持久化技术之SharedPreferences存储实例详解Android中SharedPreferences简单使用实例