首页 > 移动平台 > 详细

android第十三步采用SharedPreference保存用户偏好设置参数

时间:2014-03-14 18:43:54      阅读:490      评论:0      收藏:0      [点我收藏+]

这种存储方式是用来保存用户的设置的参数的

private Context context;

public PreferenceService(Context context) {
this.context = context;
}

public void save(String name, Integer valueOf) {
//第一个参数为文件名称,千万不要指定后缀名
SharedPreferences preferences = context.getSharedPreferences("zhao", Context.MODE_PRIVATE);
Editor editor = preferences.edit();//获取编辑器
editor.putString("name", name);
editor.putInt("age", valueOf);
editor.commit(); //一定不能忘了这句代码,把数据提交回去

}
public Map<String,String> getPreferences(){
Map<String,String> params= new HashMap<String, String>();
SharedPreferences preferences = context.getSharedPreferences("zhao", Context.MODE_PRIVATE);
params.put("name", preferences.getString("name", ""));
params.put("age",String.valueOf(preferences.getInt("age",0)));
return params;
}

public class MainActivity extends Activity {

private EditText nameText;
private EditText ageText;
PreferenceService service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nameText=(EditText)this.findViewById(R.id.name);
ageText=(EditText)this.findViewById(R.id.age);
service = new PreferenceService(getApplicationContext());
Map<String,String> params = service.getPreferences();
nameText.setText(params.get("name"));
ageText.setText(params.get("age"));
}
public void save(View v){
//this.getPreferences(MainActivity.this.MODE_PRIVATE); //可直接操作,默认名称使用Activity的名称就是MainActivity
String name = nameText.getText().toString();
String age = ageText.getText().toString();

service.save(name,Integer.valueOf(age));
Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

android第十三步采用SharedPreference保存用户偏好设置参数,布布扣,bubuko.com

android第十三步采用SharedPreference保存用户偏好设置参数

原文:http://www.cnblogs.com/zyldream/p/3598978.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!