设置两个按钮事件:
/*
* 写入偏好设置
* */
public void index_btn(View v){
Filecaozuo mfile=new Filecaozuo(this.getApplicationContext());
try {
mfile.seve_config("liyihang", 12);
Toast.makeText(getApplicationContext(), "ok", Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
/*
* 读取偏好设置
* */
public void test_btn(View v){
Filecaozuo mfile=new Filecaozuo(this.getApplicationContext());
Map<String,String> map=new HashMap<String,String>();
try {
map=mfile.read_config();
String name=map.get("name");
String age=map.get("age");
String str=name+"="+age;
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_LONG).show();
} catch (Exception e) {
// TODO Auto-generated catch block
Toast.makeText(getApplicationContext(), "no", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
业务逻辑类代码:
private Context context;
public Filecaozuo(Context context) {
this.context = context;
}
/*
* 写入偏好设置
* */
public void seve_config(String name,int age) throws Exception{
SharedPreferences parms=context.getSharedPreferences("mytool", context.MODE_PRIVATE);
Editor edit=parms.edit();
edit.putString("name", name);
edit.putInt("age", age);
edit.commit();
}
/*
* 读取偏好设置
* */
public Map<String,String> read_config() throws Exception{
SharedPreferences pre=context.getSharedPreferences("mytool", context.MODE_PRIVATE);
Map<String,String> map=new HashMap<String,String>();
map.put("name", pre.getString("name", "no"));
map.put("age", String.valueOf(pre.getInt("age", 1)));
return map;
}