7.3--SharePreferences 存储

不同于文件的存储方式,SharePreferences  是使用键值对的方式来存储数据的。也就是说当保存一条数据的时候,需要给这条数据提供一个对应的键值对,这样在读取数据的时候就可以通过这个键把相应的值取出来。而且SharePreferences 还支持多种不同的数据类型存储,如果存储的数据类型是整形,那么读取出来的数据也是整形;如果存储的数据是一个字符串,那么读取出来的数据仍然是字符串。

7.3.1 将数据存储到 SharePreferences 中

想使用SharePreferences  存储数据,首先需要获取SharePreferences 对象。Android 中主要提供了以下两种方法用于得到SharePreferences 对象。

1、Context 类中的getSharePreferences() 方法:

此方法接收两个参数:第一个参数用于指定SharePreferences 文件名称,如果指定的文件不存在则会创建一个,SharePreferences 文件都是放在/data/data/<package name>/share_prefs/目录下的;第二个参数用于指定操作模式,目前只有默认的MODE_PRIVATE 这一种模式可选,它和直接传入0的效果是相同的,表示只有当前的应用才可以对这个SharePreferences 文件进行读写,其他几种模式均已被废弃,MODE_READABLE 和MODE_WORLD_WRITEABLE 这两种模式是在Android4.2 版本中被废弃的,MODE_MULTI_PROCESS 模式是在Android6.0版本被废弃的。

2、Activity类中的getPreferences() 方法 :

这个方法和getSharePreferences() 方法很相似,不过它只接收一个操作模式参数,因为这个方法会自动将当前Activity 的类名作为SharePreferences 的文件名。

 

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

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

(2)、向SharePreferences.Editor 对象中添加数据,比如添加一个布尔类型数据就使用putBoolean() 方法,添加一个字符串就使用putString() 方法,以此类推。

(3)、调用apply()方法将添加的数据提交,从而完成数据存储操作。

接下来就是实例演示了,我们新建一个SharePreferencesTest 项目,然后修改一下activity_main.xml布局中的代码:

 

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/saveButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save Data"
        />

</LinearLayout>

简单的添加一个按钮,用于将一些数据存储到SharePreferences 文件当中,然后修改MainActivity 中的代码:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        saveButton.setOnClickListener {
            val editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit()
            editor.apply {
                putString("name","Tom")
                putInt("age",28)
                putBoolean("married",false)
                apply()
            }
        }
    }
}

接下来我们运行一下主程序就可以了,点击一下按钮,然后我们用Android Studio 去查看一下手机内存文件目录下的share_prefs文件夹:

 

7.3.2 从 SharePreferences 中读取数据

其实读取数据比存储还简单,SharePreferences 对象中提供了一系列的get 方法,用于读取存储的数据,每种get 方法都对应了SharePreferences.Editor的一种put 方法,比如读取一个布尔类型的数据就使用getBoolean()方法,读取一个字符串就用getString()方法,这些get方法都接收两个参数;第一个参数是键,第二个参数是默认值,表示当传入的键找不到对应的值就会返回我们传入的默认值。

我们继续在activity_main.xml 修改一下布局,添加一个读取按钮:

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/saveButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Save Data"
        />
    <Button
        android:id="@+id/restoreButton"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Restore Data"
        />

</LinearLayout>

然后是读取按钮的代码逻辑:

class MainActivity : AppCompatActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        saveButton.setOnClickListener {
            val editor = getSharedPreferences("data", Context.MODE_PRIVATE).edit()
            editor.apply {
                putString("name","Tom")
                putInt("age",28)
                putBoolean("married",false)
                apply()
            }
        }
        restoreButton.setOnClickListener {
            val prefs = getSharedPreferences("data", Context.MODE_PRIVATE)
            prefs.apply {
                val name = getString("name", "")
                val age = getInt("age",0)
                val married = getBoolean("married",false)
                Log.d("MainActivity","name is $name")
                Log.d("MainActivity","age is $age")
                Log.d("MainActivity","married is $married")
            }

        }
    }
}

 

这样我们就完成了,运行一下程序点击试试看吧。

 

7.3.3 实现记住密码功能

既然是实现记住密码功能,那么我们就不需要从头去写了,因为之前我们写过了一个BroadcastReceiverLogin 项目,这个项目中已经有登录界面了,我们就修改部分代码来实现这个功能。修改activity_login.xml 中的代码:

<?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:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".LoginActivity">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"
        >
        <TextView
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:textSize="18sp"
            android:text="Account:"
            />
        <EditText
            android:id="@+id/accountEdit"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center_vertical"
            />

    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="60dp"
        android:orientation="horizontal"
        >
        <TextView
            android:layout_width="90dp"
            android:layout_height="wrap_content"
            android:layout_gravity="center_vertical"
            android:textSize="18sp"
            android:text="Password:"
            />
        <EditText
            android:id="@+id/passwordEdit"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:layout_gravity="center_vertical"
            android:inputType="textPassword"
            />

    </LinearLayout>
    <LinearLayout
        android:orientation="horizontal"
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <CheckBox
            android:id="@+id/rememberPass"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            />
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="18sp"
            android:text="Remember password"
            />
    </LinearLayout>
    <Button
        android:id="@+id/login"
        android:layout_width="200dp"
        android:layout_height="60dp"
        android:layout_gravity="center_horizontal"
        android:text="Login"
        />
</LinearLayout>

在原有的基础上添加了一个CheckBox 复选框控件,我们就使用这个控件来表示用户是否需要记住密码,接下来我们来修改LoginActivity 中的代码:

class LoginActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)
        val prefs = getPreferences(Context.MODE_PRIVATE)
        val isRemember = prefs.getBoolean("remember_password", false)
        if (isRemember){
            // 将账号和密码都设置到文本中
            prefs.apply {
                accountEdit.setText(getString("account",""))
                passwordEdit.setText(getString("password",""))
                rememberPass.isChecked = true
            }
        }
        login.setOnClickListener {
            val account = accountEdit.text.toString()
            val password = passwordEdit.text.toString()
            // 如果账号是admin 且密码是 123456  就认为登录成功
            if (account == "admin" && password == "123456"){
                val editor = prefs.edit()
                if (rememberPass.isChecked){ // 检查复选框是否被选中
                    editor.apply { 
                        putBoolean("remember_password",true)
                        putString("account",account)
                        putString("password",password)
                    }
                }else{
                    editor.clear()
                }
                editor.apply()
                val intent = Intent(this,MainActivity::class.java)
                startActivity(intent)
                finish()
            }else{
                Toast.makeText(this,"account or password is invalid",Toast.LENGTH_LONG).show()
            }
        }
    }
}

这就写完了,运行一下试试看吧,大体逻辑就是初始化onCreate 的时候我们去SharePreferences 拿一次 复选框的状态,然后执行一下对应的逻辑,在提交登录的时候,我们直接拿复选框的状态,然后执行是否存储逻辑。

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值