学习|Android中SharedPreferences轻量数据存储

学更好的别人,

做更好的自己。

——《微卡智享》

本文长度为4304,预计阅读11分钟

SharedPreferences轻量数据存储

有时候我们做的App中不需要本地保存数据,但是有些小的配置参数需要记录,如果中Sqlite就感觉有点太重了,也比较麻烦,所以今天我们来看看Android系统中轻量数据存储SharedPreferences

SharedPreferences介绍

微卡智享

SharedPreferences内部是以XML的形式进行数据存储的,采用Key/value的方式 进行映射,最终会在手机的/data/data/package_name/shared_prefs/目录下,保存的数据类型有String,Int,Float和Boolean,使用起来非常的方便。

使用方法

1. 获取一个SharedPreferences,两个参数为生存的文件名和创建模式,MODE_PRIVATE:默认模式,该模式下创建的文件只能被当前应用或者与该应用具有相同SharedUserID的应用访问。别的模式也已经废弃了。

2. 通过SharedPreferences.Editor对象进行数据的更新,putstring,putint,putboolean,putfloat,再通过异步apply()或是同步commit()的方式进行数据保存。

3. 读取对象时通过getstring,getint,getboolean,getfloat的方式获取对应的保存数据

代码演示

微卡智享

布局文件

在activity_main.xml中我们用的垂直线性布局,加入一个textview,一个spinner,一个edittext和两个button

<?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:orientation="vertical"      android:padding="20dp"      tools:context=".MainActivity">        <TextView          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="Hello World!"          android:id="@+id/tvshow" />        <Spinner          android:layout_marginTop="5dp"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:id="@+id/spnitems" />          <EditText          android:layout_marginTop="5dp"          android:layout_width="match_parent"          android:layout_height="wrap_content"          android:id="@+id/edtinput" />        <Button          android:layout_marginTop="5dp"          android:id="@+id/btnwrite"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="写入数据" />        <Button          android:layout_marginTop="5dp"          android:id="@+id/btnread"          android:layout_width="wrap_content"          android:layout_height="wrap_content"          android:text="读取数据" />    </LinearLayout>

代码文件

在MainActivity的文件中,我们先定义了基本的组件,并且针对spinner生成了创建了一个字符串数组,用于保存数据的Key

然后写一个加载组件的方法

定义SharedPreferences

在onCreate中获取SharedPreferences

写入数据的方法

读取数据的方法

完整代码

package dem.vac.sharedpreferencestest    import android.content.Context  import android.content.SharedPreferences  import androidx.appcompat.app.AppCompatActivity  import android.os.Bundle  import android.text.Editable  import android.widget.*  import java.lang.Exception    class MainActivity : AppCompatActivity() {        private var listitem = arrayOf("字符", "数值", "浮点", "是非")        private val spname = "test"      private lateinit var mSharedPreferences: SharedPreferences        private lateinit var tvshow: TextView      private lateinit var btnread: Button      private lateinit var btnwrite: Button      private lateinit var edtinput: EditText      private lateinit var spinner: Spinner          override fun onCreate(savedInstanceState: Bundle?) {          super.onCreate(savedInstanceState)          setContentView(R.layout.activity_main)            mSharedPreferences = getSharedPreferences(spname, Context.MODE_PRIVATE)            InitControl()        }        //保存数据      private fun WriteData() {          val editor = mSharedPreferences.edit()          when (spinner.selectedItem.toString()) {              listitem[0] ->                  editor.putString(listitem[0], edtinput.text.toString())              listitem[1] -> {                  var int = 0;                  try {                      int = edtinput.text.toString().toInt()                  } catch (ex: Exception) {                      int = 99                      edtinput.setText("" + int)                  }                  editor.putInt(listitem[1], int)              }              listitem[2] -> {                  var float = 0f;                  try {                      float = edtinput.text.toString().toFloat()                  } catch (ex: Exception) {                      float = 1.0f                      edtinput.setText("" + float)                  }                  editor.putFloat(listitem[2], float)              }              listitem[3] -> {                  editor.putBoolean(listitem[3], edtinput.text.isNotEmpty())              }          }          editor.apply()      }        //读取数据      private fun ReadData() {          var showstr = ""          when (spinner.selectedItem.toString()) {              listitem[0] ->                  showstr = mSharedPreferences.getString(listitem[0], "无")              listitem[1] ->                  showstr = mSharedPreferences.getInt(listitem[1], -99).toString()              listitem[2] ->                  showstr = mSharedPreferences.getFloat(listitem[2], -1f).toString()              listitem[3] -> {                  showstr = mSharedPreferences.getBoolean(listitem[3], true).toString()              }          }          tvshow.setText(showstr)      }        private fun InitControl() {          tvshow = findViewById(R.id.tvshow)          edtinput = findViewById(R.id.edtinput)          btnwrite = findViewById(R.id.btnwrite)          btnwrite.setOnClickListener {              WriteData()          }          btnread = findViewById(R.id.btnread)          btnread.setOnClickListener {              ReadData()          }          spinner = findViewById(R.id.spnitems)            spinner.adapter= ArrayAdapter<String>(              this,              android.R.layout.simple_list_item_1, listitem          )      }  }

执行后我们可以看到在data/data/包名/shared_prefs中出现了test.xml的文件,说明我们执行过程中已经保存成功了

导出这个文件后我们打开看看里面的数据

以上就是SharedPreferences的简单使用方法,为了在别的程序中也可以方便使用,这里我们自己写了一个封装好的kotlin的SpHelper的类

SpHelper类

package dem.vac.sharedpreferencestest    import android.content.Context  import android.content.SharedPreferences      /**   * 作者:Vaccae   * 邮箱:[email protected]   * 创建时间:2019-12-17 13:16   * 功能模块说明:   */  class SpHelper {      companion object {          private val spFileName = "app"            fun getString(              context: Context, strKey: String?,              strDefault: String? = ""          ): String {              val setPreferences: SharedPreferences = context.getSharedPreferences(                  spFileName, Context.MODE_PRIVATE              )              return setPreferences.getString(strKey, strDefault)          }            fun putString(context: Context, strKey: String?, strData: String?) {              val activityPreferences: SharedPreferences = context.getSharedPreferences(                  spFileName, Context.MODE_PRIVATE              )              val editor = activityPreferences.edit()              editor.putString(strKey, strData)              editor.apply()          }              fun getBoolean(              context: Context, strKey: String?,              strDefault: Boolean? = false          ): Boolean {              val setPreferences: SharedPreferences = context.getSharedPreferences(                  spFileName, Context.MODE_PRIVATE              )              return setPreferences.getBoolean(strKey, strDefault!!)          }            fun putBoolean(              context: Context, strKey: String?,              strData: Boolean?          ) {              val activityPreferences: SharedPreferences = context.getSharedPreferences(                  spFileName, Context.MODE_PRIVATE              )              val editor = activityPreferences.edit()              editor.putBoolean(strKey, strData!!)              editor.apply()          }              fun getInt(context: Context, strKey: String?, strDefault: Int = -1): Int {              val setPreferences: SharedPreferences = context.getSharedPreferences(                  spFileName, Context.MODE_PRIVATE              )              return setPreferences.getInt(strKey, strDefault)          }            fun putInt(context: Context, strKey: String?, strData: Int) {              val activityPreferences: SharedPreferences = context.getSharedPreferences(                  spFileName, Context.MODE_PRIVATE              )              val editor = activityPreferences.edit()              editor.putInt(strKey, strData)              editor.apply()          }              fun getLong(context: Context, strKey: String?, strDefault: Long = -1): Long {              val setPreferences: SharedPreferences = context.getSharedPreferences(                  spFileName, Context.MODE_PRIVATE              )              return setPreferences.getLong(strKey, strDefault)          }            fun putLong(context: Context, strKey: String?, strData: Long) {              val activityPreferences: SharedPreferences = context.getSharedPreferences(                  spFileName, Context.MODE_PRIVATE              )              val editor = activityPreferences.edit()              editor.putLong(strKey, strData)              editor.apply()          }            fun getFloat(context: Context, strKey: String?, strDefault: Float = -1f): Float {              val setPreferences: SharedPreferences = context.getSharedPreferences(                  spFileName, Context.MODE_PRIVATE              )              return setPreferences.getFloat(strKey, strDefault)          }            fun putFloat(context: Context, strKey: String?, strData: Float) {              val activityPreferences: SharedPreferences = context.getSharedPreferences(                  spFileName, Context.MODE_PRIVATE              )              val editor = activityPreferences.edit()              editor.putFloat(strKey, strData)              editor.apply()          }            fun getStringSet(context: Context,strKey: String?): MutableSet<String>? {              val setPreferences: SharedPreferences = context.getSharedPreferences(                  spFileName, Context.MODE_PRIVATE              )              return setPreferences.getStringSet(strKey, LinkedHashSet<String>())          }            fun putStringSet(context: Context, strKey: String?, strData: LinkedHashSet<String>?) {              val activityPreferences: SharedPreferences = context.getSharedPreferences(                  spFileName, Context.MODE_PRIVATE              )              val editor = activityPreferences.edit()              editor.putStringSet(strKey, strData)              editor.apply()          }        }  }

扫描二维码

获取更多精彩

微卡智享

“ 往期文章 ”

分享|语音提醒来了!商盘通V2.4更新!!

学习|Android侧滑框架SmartSwipe使用

实战|仿应用宝下载并安装App(附源码)