不同于文件的存储方式,SharedPreferences提供了一种K-V键值对的数据存储方式。
也就是说,当保存一条数据的时候,需要给这条数据提供一个对应的键,这样在读取数据的时候就可以通过这个键把相应的值取出来。
而且SharedPreferences还支持多种不同的数据类型存储,如果存储的数据类型是整型,那么读取出来的数据也是整型的;如果存储的数据是一个字符串,那么读取出来的数据仍然是字符串。
实际上,SharedPreferences将保存于APP数据目录下的xml文件中,也就是以XML的格式来保存的。显然,SharedPreferences只能保存不太敏感的明文,或者采取一些加密的手段来加密数据后再存储。
下面是SharedPreferences进行数据读写的示例:
布局文件
<?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="30dp" tools:context=".SharedPreferenceActivity"> <EditText android:id="@+id/sharedPreferenceEditText" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="30dp" /> <Button android:id="@+id/sharedPreferenceWriteButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="写入数据" /> <Button android:id="@+id/sharedPreferenceReadButton" android:layout_width="match_parent" android:layout_height="wrap_content" android:text="读取数据" /> </LinearLayout>
Activity类文件
class SharedPreferenceActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_shared_preference) val editText = findViewById<EditText>(R.id.sharedPreferenceEditText) findViewById<Button>(R.id.sharedPreferenceWriteButton).setOnClickListener { val text = editText.text.toString() savePreferenceData("text", text) } findViewById<Button>(R.id.sharedPreferenceReadButton).setOnClickListener { val text = readPreferenceData("text") editText.setText(text) } } fun savePreferenceData(key: String, value: String) { val sharedPreference = getSharedPreferences("data", MODE_PRIVATE) sharedPreference.edit().apply { putString(key, value) apply() } } fun readPreferenceData(key: String): String? { val sharedPreference = getSharedPreferences("data", MODE_PRIVATE) return sharedPreference.getString(key, "") } }
总结
可以看到,我们通过 getSharedPreferences 来获取一个 SharedPreferences 实例,用于读写;在写操作中,通过调用 SharedPreferences 的 edit() 方法获取一个Editor实例,用于编辑SharedPreferences的键值(在SharedPreference的源码注释中这样说明:allowing you to modify the values in this SharedPreferences object.),然后通过putXXX来保存XXX类型的数据,如putString,最后apply()来完成更改;在读操作中,直接调用SharedPreferences的getXXX获取值数据即可。
文章评论