美文网首页
5、SharedPreferences的使用

5、SharedPreferences的使用

作者: Jarvis_zhu | 来源:发表于2017-12-20 23:59 被阅读0次

    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

    相关文章

      网友评论

          本文标题:5、SharedPreferences的使用

          本文链接:https://www.haomeiwen.com/subject/etqowxtx.html