将数据存储到SharePreferences中相比于将数据保存到文件中的好处就是区分了数据类型,使得存取更加方便。
具体代码如下:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sharepreferences);
Button save= (Button) findViewById(R.id.saveInSharePreferences);
save.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String name="小明";
int age=22;
boolean isBoy=true;
SharedPreferences sharedPreferences=getSharedPreferences("saveInSP", Context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putString("name",name);
editor.putInt("age",age);
editor.putBoolean("isBoy",isBoy);
editor.apply();
Toast.makeText(SharePreferencesActivity.this,"数据保存完毕",Toast.LENGTH_SHORT).show();
}
});
Button read= (Button) findViewById(R.id.readInSharePreferences);
read.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SharedPreferences sharedPreferences=getSharedPreferences("saveInSP",Context.MODE_PRIVATE);
String name=sharedPreferences.getString("name","");
int age=sharedPreferences.getInt("age",0);
boolean isBoy=sharedPreferences.getBoolean("isBoy",false);
Toast.makeText(SharePreferencesActivity.this,name+age+isBoy,Toast.LENGTH_SHORT).show();
}
});
}
网友评论