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()
}
}
}
}