SharedPreferences android将数据存入XML文件里实现记住密码和免登陆前奏(一)

来源:互联网 发布:热血传奇数据库 编辑:程序博客网 时间:2024/04/30 02:01

        SharedPreferences可将数据存入xml配置文件,实现文件本地的读取,是实现安卓客户端免密码登录的前奏

下边是源码:实现点击按钮保存输入框的数据到xml     

回显数据是将数据从xml文件中提取出来

PreferencesService是定义的一个工具类


MainActivity.java 

   protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        name=(EditText)findViewById(R.id.name);
        age=(EditText)findViewById(R.id.age);
        service=new PreferencesService(this); 
       
         //回显数据调出数据
         Map<String, String> params =service.getPerferences();
         name.setHint(params.get("name"));
         age.setHint(params.get("age"));
         Button bu=(Button)findViewById(R.id.button1

  }
    
    public void save(View v)
    {
   
    name1=name.getText().toString();
    age1=age.getText().toString();  
    service.save(name1,Integer.valueOf(age1));
    
    Toast.makeText(this, "保存成功", 1).show();
    });



PreferencesService代码如下

public class PreferencesService {
private Context context;


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


// 参数保存
public void save(String name1, Integer age1) {
SharedPreferences preferences = context.getSharedPreferences("itcast",
Context.MODE_PRIVATE);// 文件名称以xml文件存储,操作模式私有的
Editor editor = preferences.edit();// 调用编辑器对象编辑;
editor.putInt("age", age1);
editor.putString("name", name1);
editor.commit();
}
// 读取数据
public Map<String, String> getPerferences() {
Map<String, String> params=new HashMap<String, String>();
SharedPreferences preferences = context.getSharedPreferences("itcast",
Context.MODE_PRIVATE);
params.put("name", preferences.getString("name",""));
params.put("age",String.valueOf(preferences.getInt("age",12)));
return params;


}
}

如需源码联系527515025@qq.com

0 0
原创粉丝点击