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

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

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保存用户偏好设置参数,,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。