Android存储——SharedPreferences

SharedPreferences是什么

  • SharedPreferences是Android平台上一个轻量级的存储类,用来保存应用的一些常用配置,比如Activity状态,Activity暂停时,将此activity的状态保存到SharedPereferences中;当Activity重载,系统回调方法onSaveInstanceState时,再从SharedPreferences中将值取出

如何存储数据与读取数据

存储与读取数据数据首先要创建SharedPreferences和SharedPreferences.Editor对象
SharedPreferences sp = getSharedPreferences("everydayData", MODE_PRIVATE);
SharedPreferences.Editor editor = sp.edit();
  • 通过editor调用put方法存储数据,调用commit()方法提交
editor.putString("json", s);
editor.commit();
  • 通过SharedPreferences的get方法读取数据
sp.getString("json", "");

记住密码与自动登录案例

  • 要记住密码,我们就需要把密码储存起来,创建SharedPreferences和SharedPreferences.Editor对象
        sp = getSharedPreferences("login", MODE_PRIVATE);
        editor = sp.edit();
  • 然后进行判断是否勾选了记住密码
                //勾选了记住密码就将账号密码还有勾选状态保存
                if (jzmm.isChecked()) {
                    editor.putString("number", number.getText().toString());
                    editor.putString("psw", number.getText().toString());
                    editor.putBoolean("jzmm", true);
                } else
                    editor.putBoolean("jzmm", false);       //如果没有勾选,则勾选状态为false
                editor.commit();    //提交数据
  • 现在我们就要知道,你上一次是否勾选了记住密码,如果勾选了,那我们就把账号密码读取出来,如果没有,那就什么都不做
        if (sp.getBoolean("jzmm", false)) {
            number.setText(sp.getString("number", ""));
            psw.setText(sp.getString("psw", ""));
            jzmm.setChecked(true);      //将记住密码的勾选状态设定为true
        }
  • 现在为止,我们就实现了记住密码的功能,同时还有个自动登录的功能如下
                //判断自动登录是否勾选了,然后保存勾选状态
                if (zddl.isChecked())
                    editor.putBoolean("zddl", true);
                else
                    editor.putBoolean("zddl", false);
                editor.commit();    //提交数据
        //读取数据,判断上次登录是否勾选了自动登录
        if (sp.getBoolean("zddl", false)) {
            zddl.setChecked(true);
            //判断是否同时勾选了记住密码和自动登录,如果是,则调用myDialog()方法进行登录
            if (sp.getBoolean("zddl", false) && sp.getBoolean("jzmm", false)) {
                myDialog();
            }
        }
  • myDialog()方法
    private void myDialog() {
        //设置一个进度条
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在登录");
        progressDialog.setCancelable(true);
        //当点击取消后,flag = false
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                flag = false;
            }
        });
        //启动进度条
        progressDialog.show();
        //开启一个子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //延迟3s
                    Thread.sleep(3000);
                    //判断flag,是否点击过进度条的取消,如果没有,3s后跳转页面
                    if (flag)
                        handler.sendEmptyMessage(0);
                    //清除进度条
                    progressDialog.dismiss();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }
  • 自动登录的功能至此基本实现了,现在我们把代码整合在一起,完整的Activity代码如下
public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    private EditText number, psw;
    private CheckBox jzmm, zddl;
    private Button login_btn;
    private SharedPreferences sp;
    private SharedPreferences.Editor editor;
    private ProgressDialog progressDialog;
    private static boolean flag = true;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Intent intent = new Intent(LoginActivity.this, ContactsActivity.class);
            startActivity(intent);
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);

        bindId();
        sp = getSharedPreferences("login", MODE_PRIVATE);
        editor = sp.edit();

        if (sp.getBoolean("jzmm", false)) {
            number.setText(sp.getString("number", ""));
            psw.setText(sp.getString("psw", ""));
            jzmm.setChecked(true);      //将记住密码的勾选状态设定为true
        }
        //读取数据,判断上次登录是否勾选了自动登录
        if (sp.getBoolean("zddl", false)) {
            zddl.setChecked(true);
            //判断是否同时勾选了记住密码和自动登录,如果是,则调用myDialog()方法进行登录
            if (sp.getBoolean("zddl", false) && sp.getBoolean("jzmm", false)) {
                myDialog();
            }
        }

    }

    private void myDialog() {
        //设置一个进度条
        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("正在登录");
        progressDialog.setCancelable(true);
        //当点击取消后,flag = false
        progressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                flag = false;
            }
        });
        //启动进度条
        progressDialog.show();
        //开启一个子线程
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //延迟3s
                    Thread.sleep(3000);
                    //判断flag,是否点击过进度条的取消,如果没有,3s后跳转页面
                    if (flag)
                        handler.sendEmptyMessage(0);
                    //清除进度条
                    progressDialog.dismiss();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void bindId() {
        number = findViewById(R.id.number);
        psw = findViewById(R.id.psw);
        jzmm = findViewById(R.id.jzmm);
        zddl = findViewById(R.id.zddl);
        login_btn = findViewById(R.id.login);
        login_btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.login:
                //勾选了记住密码就将账号密码还有勾选状态保存
                if (jzmm.isChecked()) {
                    editor.putString("number", number.getText().toString());
                    editor.putString("psw", number.getText().toString());
                    editor.putBoolean("jzmm", true);
                } else
                    editor.putBoolean("jzmm", false);       //如果没有勾选,则勾选状态为false
                //判断自动登录是否勾选了
                if (zddl.isChecked())
                    editor.putBoolean("zddl", true);
                else
                    editor.putBoolean("zddl", false);
                editor.commit();    //提交数据
                flag = true;
                myDialog();
                break;
            default:
                break;
        }
    }
}
  • 布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ddd"
    android:orientation="vertical"
    tools:context="com.example.yang.paopao.LoginActivity">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#ff1133">

        <ImageView
            android:id="@+id/back"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="5dp"
            android:src="@drawable/back_btn" />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="登录"
            android:textColor="#fff"
            android:textSize="25sp" />
    </FrameLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="20dp"
        android:background="#fff"
        android:orientation="vertical">


        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dp"
                android:text="手机:"
                android:textSize="20sp" />

            <EditText
                android:id="@+id/number"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="20dp"
                android:background="@null"
                android:hint="请输入你的手机号"
                android:inputType="number" />
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#eee" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="horizontal">

            <TextView
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="20dp"
                android:text="密码:"
                android:textSize="20sp" />

            <EditText
                android:id="@+id/psw"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_margin="20dp"
                android:background="@null"
                android:hint="请输入你的密码"
                android:inputType="textPassword" />
        </LinearLayout>

        <View
            android:layout_width="match_parent"
            android:layout_height="1dp"
            android:background="#eee" />

        <LinearLayout
            android:orientation="horizontal"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <CheckBox
                android:layout_weight="1"
                android:id="@+id/jzmm"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="记住密码" />

            <CheckBox
                android:layout_weight="1"
                android:id="@+id/zddl"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginLeft="20dp"
                android:text="自动登录" />
        </LinearLayout>

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="50dp"
        android:gravity="center"
        android:orientation="horizontal">

        <Button
            android:id="@+id/login"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/rgister_btn_bk"
            android:text="登录"
            android:textColor="#fff"
            android:textSize="20sp" />

        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="50dp"
            android:background="@drawable/rgister_btn_bk"
            android:text="注册"
            android:textColor="#fff"
            android:textSize="20sp" />
    </LinearLayout>
</LinearLayout>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值