5、SharedPreferences的使用

SharedPreferences可以存储一些简单的数据在应用里面

使用步骤:

1.得到实例

// [2.4]使用SharedPreferences 去保存数据 拿到sp的实例
// name 会帮助我们生成一个xml文件
sp = getSharedPreferences("config", MODE_PRIVATE);

2.写入数据并且提交

            // [2.5]获取sp的编辑器
            Editor editor = sp.edit();
            if (cb_ischeck.isChecked()) {

                editor.putString("name", name);
                editor.putString("pwd", pwd);
                editor.putBoolean("save", true);

            } else {
                Toast.makeText(MainActivity.this, "请勾选", Toast.LENGTH_LONG).show();
                editor.putBoolean("save", false);
            }
            // [2.6]记得把editor提交
            editor.commit();
  1. 获取数据并显示
        // [1.1]在config.xml文件中把数据取出来,显示到edittext
        boolean save = sp.getBoolean("save", false);
        if (save) {
            String name = sp.getString("name", "");
            String pwd = sp.getString("pwd", "");
            et_name.setText(name);
            et_pwd.setText(pwd);
            cb_ischeck.setChecked(true);
        }

SharedPreferences在项目里面生成的xml文件如图:

生成的xml文件.png
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容