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

    开机就会补全帐号密码

  • 相关阅读:
    hdu5945 Fxx and game
    hdu5937 Equation
    2016-2017 CT S03E06: Codeforces Trainings Season 3 Episode 6 The Baguette Master
    Canada Cup 2016 D. Contest Balloons
    hdu5798 Stabilization
    bzoj 4026 dC Loves Number Theory
    Intel Code Challenge Final Round (Div. 1 + Div. 2, Combined) C. Ray Tracing
    hdu5923 Prediction
    hdu5925 Coconuts
    2016弱校联盟十一专场10.2 Longest Increasing Subsequence
  • 原文地址:https://www.cnblogs.com/wzben/p/6068763.html
Copyright © 2020-2023  润新知