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

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

上一篇:win10系统下共享WIFI热点后手机无法连接如何解决


下一篇:Android——build.gradle文件