前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >学习|Android中SharedPreferences轻量数据存储

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

作者头像
Vaccae
修改2020-01-03 14:40:30
6470
修改2020-01-03 14:40:30
举报
文章被收录于专栏:微卡智享微卡智享

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

代码语言:javascript
复制
<?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

写入数据的方法

读取数据的方法

完整代码

代码语言:javascript
复制
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类

代码语言:javascript
复制
package dem.vac.sharedpreferencestest

import android.content.Context
import android.content.SharedPreferences


/**
 * 作者:Vaccae
 * 邮箱:3657447@qq.com
 * 创建时间: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()
        }

    }
}
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2019-12-23,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 微卡智享 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
对象存储
对象存储(Cloud Object Storage,COS)是由腾讯云推出的无目录层次结构、无数据格式限制,可容纳海量数据且支持 HTTP/HTTPS 协议访问的分布式存储服务。腾讯云 COS 的存储桶空间无容量上限,无需分区管理,适用于 CDN 数据分发、数据万象处理或大数据计算与分析的数据湖等多种场景。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档