欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android 共享参数 SharedPreferences

程序员文章站 2023-10-29 11:51:10
完成共享参数的读写public class SharedPreference { private Context context; public SharedPreference(Context context) { // TODO Auto-generated constructor stub t... ......

完成共享参数的读写

public class sharedpreference {

    private context context;

    public sharedpreference(context context) {
        // todo auto-generated constructor stub

        this.context = context;
    }

    public boolean savemessage(string name, string passwd) {

        boolean flag = false;

        // 自动保存成 userinfo.xml
        sharedpreferences sharedpreferences = context.getsharedpreferences("userinfo", context.mode_private);

        // 对数据进行编辑
        sharedpreferences.editor editor = sharedpreferences.edit();
        editor.putstring("name", name);
        editor.putstring("passwd", passwd);
        // 将数据持久化到存储介质中
        flag = editor.commit();
        return flag;
    }

    public map<string, object> getmessage() {
        map<string, object> map = new hashmap<string, object>();
        sharedpreferences sharedpreferences = context.getsharedpreferences("userinfo", context.mode_private);

        string name = sharedpreferences.getstring("name", "");
        string passwd = sharedpreferences.getstring("passwd", "");

        map.put("name", name);
        map.put("passwd", passwd);

        return map;
    }
}

编写测试函数

    private button button1;
    private button button2;

    @override
    protected void oncreate(bundle savedinstancestate) {
        super.oncreate(savedinstancestate);
        setcontentview(r.layout.activity_main);

        button1 = (button) findviewbyid(r.id.button1);

        button1.setonclicklistener(new view.onclicklistener() {

            @override
            public void onclick(view v) {
                // todo auto-generated method stub

                sharedpreference sharedpreference = new sharedpreference(mainactivity.this);
                boolean flag = sharedpreference.savemessage("furong", "123456");

                toast.maketext(mainactivity.this, "---->" + flag, 1).show();
            }
        });

        button2 = (button) findviewbyid(r.id.button2);
        button2.setonclicklistener(new view.onclicklistener() {

            @override
            public void onclick(view v) {
                // todo auto-generated method stub
                map<string, object> map;

                sharedpreference sharedpreference = new sharedpreference(mainactivity.this);
                map = sharedpreference.getmessage();

                toast.maketext(mainactivity.this, map.tostring(), 1).show();
            }
        });
    }

写测试

读测试