SharePreferences 使用键值存储方式,每条数据都包含 key 和 value。 每个应用都会有一个默认的 SharePreferences 文件,可以在这里保存键值。也可以指定文件名进行保存。 PreferenceManager.getDefaultSharedPreferences(this) getSharedPreferences("company", Activity.MODE_PRIVATE) 先写一个保存信息的例子
- //保存数据
- btnMnPreferencesSaveData.setOnClickListener {
- //获得 SharePreferences 对象
- var sharePreferences = getSharedPreferences("company", Activity.MODE_PRIVATE)
- //获得 SharePreferences.Editor 对象
- var editor = sharePreferences.edit()
- //使用 putXxx 方法保存键值
- editor.putInt("id", 1)
- editor.putString("name", "金龙翼")
- editor.putString("url", "http://www.cofox.com")
- editor.putString("city", "太原")
- editor.putString("wx", "hotu2010")
- //保存数据在文件中
- editor.commit()
- Toast.makeText(this, "数据保存成功!", Toast.LENGTH_SHORT).show()
- }
这是一个按钮点击的实现代码。 然后,我们再用另一个按钮取出数据看看。
- //读取数据
- btnMnPreferencesReadData.setOnClickListener {
- var sharePreferences = getSharedPreferences("company", Activity.MODE_PRIVATE)
- //使用 getString 或 getInt 方法获得 value
- var id = sharePreferences.getInt("id", 0)
- var name = sharePreferences.getString("name", "")
- var url = sharePreferences.getString("url", "")
- var city = sharePreferences.getString("city", "")
- var wx = sharePreferences.getString("wx", "")
- var phone = sharePreferences.getString("phone", "")
- //显示获取的数据
- Toast.makeText(this, id.toString()+ " - " + name + " - " + url + " - " + city + " - " + wx + " - " + phone, Toast.LENGTH_SHORT).show()
- }
为什么会比添加数据多了一个 phone 的键呢? 这是我要重点说的。 这里需要记得,当你的程序更新了的时候,保存的信息一般并不会被清理掉(原应用不是被卸载的)。新的信息修改进去只是增加,不会对未编辑的信息做改动。 测试步骤: 1、当第一次写入信息的时候,editor.putString("phone", "13912345687") 是其中一个键值。 2、编译运行,观察取出的数据。 3、再次修改代码,editor.putString("phone", "13912345687") 修改为 editor.putString("wx", "hotu2010") 4、编译运行,观察取出的数据。 你会发现 phone 仍然是存在的。
来看一个实际的例子,登录保存用户名密码,以便下次不用再输入了。 首先构建界面
- <?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"
- tools:context="com.cofox.functions.SharePreferences.SharePreferencesActivity">
- <Button
- android:id="@+id/btnMnPreferencesSaveData"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="保存数据"
- tools:layout_editor_absoluteX="109dp"
- tools:layout_editor_absoluteY="83dp" />
- <Button
- android:id="@+id/btnMnPreferencesReadData"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="读取数据" />
- <View
- android:id="@+id/viewLine"
- android:layout_width="match_parent"
- android:layout_height="1dp"
- android:background="#ccc"/>
- <LinearLayout
- android:id="@+id/linearlayout_Login"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:orientation="vertical">
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
- <TextView
- android:layout_width="60dp"
- android:layout_height="wrap_content"
- android:gravity="right"
- android:text="用户名:"/>
- <EditText
- android:id="@+id/edttxtUserName"
- android:layout_width="0dp"
- android:layout_height="wrap_content"
- android:layout_weight="1"/>
- </LinearLayout>
- <LinearLayout
- android:layout_width="match_parent"
- android:layout_height="wrap_content">
- <TextView
- android:layout_width="60dp"
- android:layout_height="wrap_content"
- android:gravity="right"
- android:text="密码:"/>
- <EditText
- android:id="@+id/edttxtPwd"
- android:layout_width="0dp"
- android:layout_height="wrap_content"
- android:layout_weight="1"
- android:inputType="textPassword"/>
- </LinearLayout>
- <CheckBox
- android:id="@+id/chckboxSave"
- android:layout_width="wrap_content"
- android:layout_height="wrap_content"
- android:text="保存用户名和密码"
- android:layout_marginLeft="10dp"/>
- <Button
- android:id="@+id/btnLogin"
- android:layout_width="match_parent"
- android:layout_height="wrap_content"
- android:text="登录"
- android:layout_margin="10dp"/>
- </LinearLayout>
- </LinearLayout>
登录界面
在 onCreate 内增加登录按钮的点击操作
- //登录操作
- btnLogin.setOnClickListener {
- myLogin()
- }
myLogin() 代码
- /**
- * Cofox 登录
- * created at 2017/12/29 22:28
- * 功能描述:
- * 用户名和密码正确
- * 登录成功后,如果选中了CheckBox则保存用户名和密码
- * 用户名或密码不正确
- * 弹出提示信息(未实现)
- * file:SharePreferencesActivity.kt
- *
- *
- * 修改历史:
- * 2017/12/29:
- *
- */
- fun myLogin(){
- var sharepreferences = PreferenceManager.getDefaultSharedPreferences(this)
- var username = edttxtUserName.text.toString()
- var password = edttxtPwd.text.toString()
- //如果登录成功
- if (true) {
- //根据选择情况,来决定是否保存用户名和密码
- if (chckboxSave.isChecked) {
- var editor = sharepreferences.edit()
- editor.putString("username", username)
- editor.putString("password", password)
- editor.commit()
- Toast.makeText(this, "登录成功,用户名和密码已保存!", Toast.LENGTH_LONG).show()
- } else {
- var editor = sharepreferences.edit()
- editor.putString("username", "")
- editor.putString("password", "")
- editor.commit()
- Toast.makeText(this, "登录成功!", Toast.LENGTH_LONG).show()
- }
- }
- }
其中,登录的用户名密码没有做验证。真实项目需要补上这一环节。另,密码应当加密存储。不是本文研究范围。 这段代码实现了点击的操作。如果选择了保存,就会保存到默认文件;如果没有选择保存,就会清空已经保存的旧信息。 还需要实现另一个功能,就是当界面展开的时候,如果有保存了的用户名和密码信息,就填写到相应的位置。 这段代码没有打包成函数,直接写在 onCreate 里了。
- //用户名和密码调出显示
- var sharepreferences = PreferenceManager.getDefaultSharedPreferences(this)
- var username = sharepreferences.getString("username", "")
- var password = sharepreferences.getString("password", "")
- edttxtUserName.setText(username)
- edttxtPwd.setText(password)
- try {
- if (username.length > 0){
- chckboxSave.isChecked = true
- }
- } catch (e: Exception) {
- }
之所以用了 try catch 是预防 username 不存在的情况。
全部代码
- package com.cofox.functions.SharePreferences
- import android.app.Activity
- import android.support.v7.app.AppCompatActivity
- import android.os.Bundle
- import android.preference.PreferenceManager
- import android.widget.Toast
- import com.cofox.mykt.myweather.R
- import kotlinx.android.synthetic.main.activity_share_preferences.*
- class SharePreferencesActivity : AppCompatActivity() {
- override fun onCreate(savedInstanceState: Bundle?) {
- super.onCreate(savedInstanceState)
- setContentView(R.layout.activity_share_preferences)
- //用户名和密码调出显示
- var sharepreferences = PreferenceManager.getDefaultSharedPreferences(this)
- var username = sharepreferences.getString("username", "")
- var password = sharepreferences.getString("password", "")
- edttxtUserName.setText(username)
- edttxtPwd.setText(password)
- try {
- if (username.length > 0){
- chckboxSave.isChecked = true
- }
- } catch (e: Exception) {
- }
- //保存数据
- btnMnPreferencesSaveData.setOnClickListener {
- //获得 SharePreferences 对象
- var sharePreferences = getSharedPreferences("company", Activity.MODE_PRIVATE)
- //获得 SharePreferences.Editor 对象
- var editor = sharePreferences.edit()
- //使用 putXxx 方法保存键值
- editor.putInt("id", 1)
- editor.putString("name", "金龙翼")
- editor.putString("url", "http://www.cofox.com")
- editor.putString("city", "太原")
- editor.putString("phone", "13912345687")
- editor.putString("wx", "hotu2010")
- //保存数据在文件中
- editor.commit()
- Toast.makeText(this, "数据保存成功!", Toast.LENGTH_SHORT).show()
- }
- //读取数据
- btnMnPreferencesReadData.setOnClickListener {
- var sharePreferences = getSharedPreferences("company", Activity.MODE_PRIVATE)
- //使用 getString 或 getInt 方法获得 value
- var id = sharePreferences.getInt("id", 0)
- var name = sharePreferences.getString("name", "")
- var url = sharePreferences.getString("url", "")
- var city = sharePreferences.getString("city", "")
- var wx = sharePreferences.getString("wx", "")
- var phone = sharePreferences.getString("phone", "")
- //显示获取的数据
- Toast.makeText(this, id.toString()+ " - " + name + " - " + url + " - " + city + " - " + wx + " - " + phone, Toast.LENGTH_SHORT).show()
- }
- //登录操作
- btnLogin.setOnClickListener {
- myLogin()
- }
- }
- ///////////////////////////////////////////////////
- /**
- * Cofox 登录
- * created at 2017/12/29 22:28
- * 功能描述:
- * 用户名和密码正确
- * 登录成功后,如果选中了CheckBox则保存用户名和密码
- * 用户名或密码不正确
- * 弹出提示信息(未实现)
- * file:SharePreferencesActivity.kt
- *
- *
- * 修改历史:
- * 2017/12/29:
- *
- */
- fun myLogin(){
- var sharepreferences = PreferenceManager.getDefaultSharedPreferences(this)
- var username = edttxtUserName.text.toString()
- var password = edttxtPwd.text.toString()
- //如果登录成功
- if (true) {
- //根据选择情况,来决定是否保存用户名和密码
- if (chckboxSave.isChecked) {
- var editor = sharepreferences.edit()
- editor.putString("username", username)
- editor.putString("password", password)
- editor.commit()
- Toast.makeText(this, "登录成功,用户名和密码已保存!", Toast.LENGTH_LONG).show()
- } else {
- var editor = sharepreferences.edit()
- editor.putString("username", "")
- editor.putString("password", "")
- editor.commit()
- Toast.makeText(this, "登录成功!", Toast.LENGTH_LONG).show()
- }
- }
- }
- }
来源: http://www.jianshu.com/p/613eb3d890f3