Android采用SharedPreferences保存用户偏好设置参数
2013-01-07 21:28
483 查看
MainActivity类的内容
PreferencesService类的内容
public class MainActivity extends Activity { EditText nameValue = null; EditText ageValue = null; PreferencesService service = null; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); nameValue = (EditText) findViewById(R.id.name_id); //获取名字输入框id ageValue = (EditText) findViewById(R.id.age_id); //获取年龄输入框id service = new PreferencesService(getApplication()); Map<String, String> map = service.getPreferenves(); nameValue.setText(map.get("name")); //获得配置参数name ageValue.setText(map.get("age")); //获得配置参数age } public void save(View v) throws Exception { String name = nameValue.getText().toString(); //获取输入的名字 String age = ageValue.getText().toString(); //获取输入的年龄 service.save(name, Integer.valueOf(age)); //执行保存方法 Toast.makeText(getApplicationContext(), R.string.success, Toast.LENGTH_LONG).show(); //吐丝显示保存成功 } }
PreferencesService类的内容
public class PreferencesService { Context context; public PreferencesService(Context context) { this.context = context; } /** * 保存参数 * @param name 姓名 * @param age 年龄 */ public void save(String name, Integer age) { //确定文件名称,并把文件读写设置成Context.MODE_PRIVATE SharedPreferences preferences = context.getSharedPreferences("itcast",Context.MODE_PRIVATE ); //创建xml编辑器 Editor editor = preferences.edit(); editor.putString("name", name); //第一个参数是为xml节点起名字,第二个参数是为节点写入值 editor.putInt("age", age); editor.commit(); //未调用该方法之前,信息存储在内存中,调用后写成xml文件 } /** * 获取各项配置参数 * @return */ public Map<String,String> getPreferenves (){ Map<String, String> map = new HashMap<String, String>(); SharedPreferences preferences = context.getSharedPreferences("itcast",Context.MODE_PRIVATE ); map.put("name", preferences.getString("name", "")); map.put("age", String.valueOf(preferences.getInt("age", 0))); return map; } }
相关文章推荐
- Android开发入门之采用SharedPreferences保存用户偏好设置参数
- 保存、方法-Android文件存储--采用SharedPreferences保存用户偏好设置参数和读取设置参数-by小雨
- Android采用SharedPreferences保存用户偏好设置参数
- android第十三步采用SharedPreference保存用户偏好设置参数
- Android文件存储--采用SharedPreferences保存用户偏好设置参数和读取设置参数
- 采用SharedPreferences保存用户偏好设置参数
- 16_采用SharedPreferences保存用户偏好设置参数
- 采用SharedPreferences保存用户偏好设置参数
- Android学习16_采用SharedPerferences保持用户偏好设置参数
- 16_采用SharedPreferences保存用户偏好设置参数
- 采用SharedPreference保存用户偏好参数设置
- Android学习笔记---16_采用SharedPreferences保存用户偏好设置参数
- 实例教程五:采用SharedPreferences保存用户偏好设置参数
- 实例教程五:采用SharedPreferences保存用户偏好设置参数
- 实例教程五:采用SharedPreferences保存用户偏好设置参数
- Android心得4.2--SharedPreference保存用户偏好参数设置.doc
- Android文件存储--采用SharedPreferences保存用户偏好设置
- Android 保存用户偏好设置
- Android 保存用户偏好设置
- Android基础入门教程——6.2 数据存储与访问之——SharedPreferences保存用户偏好参数