• SharePreferences基本用法


    Android提供的轻量级数据储存方法,一般存少量数据,比如配置什么的。方式是通过键值对存取,比较方便。

    下面通过一个 记住密码 的简单例子来说明

    public class MainActivity extends AppCompatActivity {
    
        EditText user;
        EditText psw;
        Button button;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            user = (EditText)findViewById(R.id.user);
            psw = (EditText)findViewById(R.id.psw);
            button = (Button)findViewById(R.id.button);
    
            //启动的时候读取SharePerences,读取data这个文件,访问模式私有
            SharedPreferences preferences = getSharedPreferences("data",MODE_PRIVATE);
    //读取数据,判断有没有点击记住密码 boolean isRemember = preferences.getBoolean("remember",false); if(isRemember){ Log.d("TAG","remember");
           //读取数据 String u = preferences.getString("user",""); String p = preferences.getString("psw",""); user.setText(u); psw.setText(p); } button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String u = user.getText().toString(); String p = psw.getText().toString();
              //创建,注意和读取的时候不同,这个是edit,两个参数分别为存储数据的文件data,访问模式私有 SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
              //存数据 editor.putString("user",u); editor.putString("psw",p); editor.putBoolean("remember",true);
              //提交 editor.commit(); } }); } }

    开机就会补全帐号密码

  • 相关阅读:
    CURL常用命令
    极客无极限 一行HTML5代码引发的创意大爆炸
    JS的prototype和__proto__(含es6的class)
    leetcode 44:construct-binary-tree-from-preorder-and-inorder
    leetcode 43:construct-binary-tree-from-inorder-and-postorder
    leetcode 42:binary-tree-level-order-traversal-ii
    leetcode 38:path-sum
    leetcode 37:path-sum-ii
    leetcode 33:pascals-triangle
    leetcode 32:pascals-triangle-ii
  • 原文地址:https://www.cnblogs.com/wzben/p/6068763.html
Copyright © 2020-2023  润新知