SharedPreferences基本使用--看完你就会用了

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

01. Context类中的getSharedPreferences()方法

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

02. Activity类中的getPreferences()方法

        这个方法和Context中的getSharedPreferences()方法很相似,不过它只接收一个操
作模式参数,因为使用这个方法时会自动将当前Activity的类名作为
SharedPreferences的文件名。
        得到了SharedPreferences对象之后,就可以开始向SharedPreferences文件中存储数
据了,主要可以分为3步实现。
        (1) 调用SharedPreferences对象的edit()方法获取一个
SharedPreferences.Editor对象。
        (2) 向SharedPreferences.Editor对象中添加数据,比如添加一个布尔型数据就使用
putBoolean()方法,添加一个字符串则使用putString()方法,以此类推。
        (3) 调用apply()或commit()方法将添加的数据提交,从而完成数据存储操作。

note:apply()是异步提交或commit()是同步提交

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()  //当然也        可以不指定sp name
            editor.putString("name", "Tom")
            editor.putInt("age", 28)
            editor.putBoolean("married", false)
            editor.apply()
        }
    }
}

例子:实现一个自动登陆功能,当用户在checkbox后下次登陆会自动输入账户和密码

package com.example.sharepreference

import android.content.Context
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.widget.Toast
import com.example.sharepreference.databinding.ActivityMainBinding

class MainActivity : AppCompatActivity() {
    lateinit var binding:ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root.rootView)
        val prefs = getPreferences(Context.MODE_PRIVATE)
        val isRemember = prefs.getBoolean("remember_password",false)
        if(isRemember){
            val account = prefs.getString("account","")
            val password = prefs.getString("password","")
            binding.accountEdit.setText(account)
            binding.passwordEdit.setText(password)
            binding.rememberPass.isChecked = true
        }
        binding.login.setOnClickListener{
            val edit = prefs.edit()
            if(binding.accountEdit.text.toString() == "admin"&&
                binding.passwordEdit.text.toString()=="123456"){
                if(binding.rememberPass.isChecked){
                    edit.putString("password",binding.passwordEdit.text.toString())
                    edit.putString("account",binding.accountEdit.text.toString())
                    edit.putBoolean("remember_password",true)
                }else{
                    edit.putBoolean("remember_password",false)
                }
                edit.apply()
                val i = Intent(this,SecondActivity::class.java)
                startActivity(i)
                finish()
            }else{
                Toast.makeText(this, "loading fail", Toast.LENGTH_SHORT).show()
                binding.passwordEdit.setText("")
            }
        }
    }
}
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.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=".MainActivity">

    <EditText
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="50dp"
        android:hint="Please input save data"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_bias="0.1" />

    <Button
        android:id="@+id/save"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="save"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/text"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintVertical_bias="0.1"
        app:layout_constraintHorizontal_bias="0.333" />
    <Button
        android:id="@+id/show"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="show"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/text"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintVertical_bias="0.1"
        app:layout_constraintHorizontal_bias="0.666" />
</androidx.constraintlayout.widget.ConstraintLayout>

  • 3
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值