【笔记】Android数据存储——SharedPreferences

本博文为《第一行代码》、《爱上Android》读书笔记,供个人备忘用。

适用范围:保存少量的数据,且这些数据的格式非常简单:字符串型、基本类型的值。比如应用程序的各种配置信息(如是否打开音效、是否使用震动效果、小游戏的玩家积分等),解锁口令密码等。

核心原理:保存基于XML文件存储的key-value键值对数据,通常用来存储一些简单的配置信息。

Android 系统中SharedPreferences文件都是存放在:/data/data/PACKAGE_NAME /shared_prefs 目录下的。

创建SharedPreferences的三种方法:

1、Context类中的 getSharedPreferences() 方法:此方法接收两个参数,第一个参数用于指定SharedPreferences文件的名称,如果指定的文件不存在则会创建一个。第二个参数用于指定操作模式,目前只有MODE_PRIVATE这一种模式可选,它是默认的操作模式,和直接传入0效果是相同的,表示只有当前的应用程序才可以对这个SharedPreferences文件进行读写。其他几种操作模式均已被废弃,MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE这两种模式是在Android 4.2 被废弃的,MODE_MULTI_PROCESS是在Android 6.0版本中被废弃的。

2、Activity类中的 getPreferences() 方法:这个方法和 Context 中的 getSharedPreferences() 方法很相似,只不过它只接收一个操作模式参数,因为使用这个方法时会自动将当前活动的类名作为SharedPreferences的文件名。

3、PreferenceManager类中的 getDefaultSharedPreference() 方法:这是一个静态方法,它接收一个Context参数,并自动使用当前应用程序的包名作为前缀来命名SharedPreferences的文件。

得到了SharedPreferences对象之后,就可以开始向 SharedPreferences 文件中存储数据了,主要可以分为3步实现:

1、调用 SharedPreferences 对象的 edit() 方法来获取一个 SharedPreferences.Editor 对象

2、向 SharedPreferences.Editor 对象添加数据。

3、调用 apply() 或 commit() 提交数据, 其中apply()效率快,但是线程不安全不适合多线程中操作,edit.commit()线程安全,但是效率慢,推荐使用apply();

实例(实现记住密码功能):

先看效果图:
这里写图片描述

这里写图片描述

布局代码:

activity_login.xml 的布局很简单,两个输入框,一个复选框,一个按钮:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText
        android:id="@+id/user_name"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/edittext_bg"
        android:gravity="center_vertical"
        android:hint="请输入用户名"
        android:paddingLeft="12dp" />

    <EditText
        android:id="@+id/psw"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="20dp"
        android:background="@drawable/edittext_bg"
        android:gravity="center_vertical"
        android:hint="请输入密码"
        android:inputType="textPassword"
        android:paddingLeft="12dp" />

    <CheckBox
        android:id="@+id/check_box"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="10dp"
        android:text="记住密码"
        android:textSize="16dp" />

    <Button
        android:id="@+id/login"
        android:layout_width="match_parent"
        android:layout_height="45dp"
        android:layout_marginLeft="20dp"
        android:layout_marginRight="20dp"
        android:layout_marginTop="30dp"
        android:background="@color/colorPrimary"
        android:text="Login"
        android:textColor="#fff" />

</LinearLayout>

activity_main.xml 只显示跳转成功提示语:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout 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"
    tools:context="com.lanbots.sharedpreferencesdemo.MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello lanbots!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

java代码:

LoginActivity.java :

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;

/**
 * Created by lanbots on 2017/10/10.
 * Email : lanbots@lanbots.cn
 * Blog : www.lanbots.xin
 */

public class LoginActivity extends AppCompatActivity {

    public static final String REMEMBER_PASSWORD = "remember_password";
    public static final String ACCOUNT = "account";
    public static final String PASSWORD = "password";

    private EditText mUserName, mPassword;
    private CheckBox mRememberPsw;
    private Button mLogin;

    private SharedPreferences spf;
    private SharedPreferences.Editor editor;


    private boolean isRemember;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //初始化
        initView();
        //获取SharedPreferences对象
        spf = PreferenceManager.getDefaultSharedPreferences(this);

        isRemember = spf.getBoolean(REMEMBER_PASSWORD, false);

        if (isRemember) {
            //讲账号和密码都设置到TextView中
            String account = spf.getString(ACCOUNT, "");
            String passworrd = spf.getString(PASSWORD, "");
            mUserName.setText(account);
            mPassword.setText(passworrd);
            mRememberPsw.setChecked(true);
        }

        //登入点击事件
        mLogin.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String account = mUserName.getText().toString();
                String password = mPassword.getText().toString();
                //如果账号是:lanbots,密码是:123456,就认为登入成功
                if (account.equals("lanbots") && password.equals("123456")) {
                    //取SharedPreferences.Editor 对象 
                    editor = spf.edit();
                    if (mRememberPsw.isChecked()) {
                        //检查复选框是否选中,选中则向SharedPreferences.Editor 对象中添加数据
                        editor.putBoolean(REMEMBER_PASSWORD, true);
                        editor.putString(ACCOUNT, account);
                        editor.putString(PASSWORD, password);
                    } else {
                        editor.clear();
                    }
                    editor.apply(); //提交数据
                    //进行跳转,并finish当前activity
                    startActivity(new Intent(LoginActivity.this, MainActivity.class));
                    finish();
                } else {
                    Toast.makeText(LoginActivity.this,"用户名或密码错误",Toast.LENGTH_SHORT).show();
                }
            }
        });

    }

    private void initView() {
        mUserName = (EditText) findViewById(R.id.user_name);
        mPassword = (EditText) findViewById(R.id.psw);
        mRememberPsw = (CheckBox) findViewById(R.id.check_box);
        mLogin = (Button) findViewById(R.id.login);
    }


}

MainActivity.java:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

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

以上就是该例子的全部代码,需要项目源码的请到这里下载

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值