Android 共享参数 SharedPreferences

完成共享参数的读写

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();
            }
        });
    }

写测试

image

读测试

image

posted @ 2019-11-06 16:43  thomas_blog  阅读(574)  评论(0编辑  收藏  举报