學習|Android中SharedPreferences輕量數據存儲
- 2020 年 1 月 2 日
- 筆記
學更好的別人,
做更好的自己。
——《微卡智享》
本文長度為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() } } }
完
掃描二維碼
獲取更多精彩
微卡智享
「 往期文章 」