Android 数据保存 - SharedPreferences

2024-06-21 15:32

本文主要是介绍Android 数据保存 - SharedPreferences,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

参考:

保存数据:https://developer.android.com/training/basics/data-storage/index.html


在应用过程中,可能会产生多种不同类型的数据,有些数据需要重复使用。Android 系统提供了多种方式来保存数据,包括使用 SharedPreferences API 保存共享首选项,保存本地文件以及数据库操作


主要内容

  1. SharedPreferences API
  2. SharedPreferencesUtil.java

SharedPreferences API

参考:

保存键值集

使用共享首选项

SharedPreferences

SharedPreferences API 可以 保存和检索原始数据类型的永久性键值对

原始数据类型包括

  • 布尔值
  • 浮点值
  • 整型值
  • 长整型
  • 字符串

获取 SharedPreferences 对象

创建新的共享首选项文件或访问现有的文件,可通过以下两种方法:

  • getSharedPreferences() — 如果您需要按照您用第一个参数指定的名称识别的多个共享首选项文件,请使用此方法。您可以从您的应用中的 任何 Context 调用此方法
  • getPreferences() — 如果您只需使用 Activity 的一个共享首选项,请从 Activity 中使用此方法。 因为此方法会检索属于该 Activity 的默认共享首选项文件,您无需提供名称

方法一:

/*** Retrieve and hold the contents of the preferences file 'name', returning* a SharedPreferences through which you can retrieve and modify its* values.  Only one instance of the SharedPreferences object is returned* to any callers for the same name, meaning they will see each other's* edits as soon as they are made.** @param name Desired preferences file. If a preferences file by this name* does not exist, it will be created when you retrieve an* editor (SharedPreferences.edit()) and then commit changes (Editor.commit()).* @param mode Operating mode.  Use 0 or {@link #MODE_PRIVATE} for the* default operation.** @return The single {@link SharedPreferences} instance that can be used*         to retrieve and modify the preference values.** @see #MODE_PRIVATE*/
public abstract SharedPreferences getSharedPreferences(String name, int mode);

参数 name 表示共享首选项文件名,如果不存在该共享首选项文件,则新建

参数 mode 表示文件操作模式,使用 0 或者 Context.MODE_PRIVATE 表示仅本应用可访问

方法二:

/*** Retrieve a {@link SharedPreferences} object for accessing preferences* that are private to this activity.  This simply calls the underlying* {@link #getSharedPreferences(String, int)} method by passing in this activity's* class name as the preferences name.** @param mode Operating mode.  Use {@link #MODE_PRIVATE} for the default*             operation.** @return Returns the single SharedPreferences instance that can be used*         to retrieve and modify the preference values.*/
public SharedPreferences getPreferences(int mode) {return getSharedPreferences(getLocalClassName(), mode);
}

就是默认使用 Activity 名作为方法一中的 name

写入共享首选项

  • SharedPreferences 对象中调用方法 edit 得到 SharedPreferences.Editor

    /*** Create a new Editor for these preferences, through which you can make* modifications to the data in the preferences and atomically commit those* changes back to the SharedPreferences object.* * <p>Note that you <em>must</em> call {@link Editor#commit} to have any* changes you perform in the Editor actually show up in the* SharedPreferences.* * @return Returns a new instance of the {@link Editor} interface, allowing* you to modify the values in this SharedPreferences object.*/
    Editor edit();
    
  • 调用 SharedPreferences.Editor 中的方法输入键值对

    putBoolean(String key, boolean value)
    putFloat(String key, float value)
    putInt(String key, int value)
    putLong(String key, long value)
    putString(String key, String value)
    putStringSet(String key, Set<String> values)
    
  • 修改完成后,调用方法 commit() 提交

    /*** Commit your preferences changes back from this Editor to the* {@link SharedPreferences} object it is editing.  This atomically* performs the requested modifications, replacing whatever is currently* in the SharedPreferences.** <p>Note that when two editors are modifying preferences at the same* time, the last one to call commit wins.** <p>If you don't care about the return value and you're* using this from your application's main thread, consider* using {@link #apply} instead.** @return Returns true if the new values were successfully written* to persistent storage.*/
    boolean commit();
    

    Note:使用同一 name 检索得到的是同一个共享首选项文件,如果多个 Editor 同时编辑并提交,后面一个会覆盖前面的(这个是注释的内容,应该是说相同键的会覆盖)

  • 也可以使用方法 apply() 提交:

        /*** Commit your preferences changes back from this Editor to the* {@link SharedPreferences} object it is editing.  This atomically* performs the requested modifications, replacing whatever is currently* in the SharedPreferences.** <p>Note that when two editors are modifying preferences at the same* time, the last one to call apply wins.** <p>Unlike {@link #commit}, which writes its preferences out* to persistent storage synchronously, {@link #apply}* commits its changes to the in-memory* {@link SharedPreferences} immediately but starts an* asynchronous commit to disk and you won't be notified of* any failures.  If another editor on this* {@link SharedPreferences} does a regular {@link #commit}* while a {@link #apply} is still outstanding, the* {@link #commit} will block until all async commits are* completed as well as the commit itself.** <p>As {@link SharedPreferences} instances are singletons within* a process, it's safe to replace any instance of {@link #commit} with* {@link #apply} if you were already ignoring the return value.** <p>You don't need to worry about Android component* lifecycles and their interaction with <code>apply()</code>* writing to disk.  The framework makes sure in-flight disk* writes from <code>apply()</code> complete before switching* states.** <p class='note'>The SharedPreferences.Editor interface* isn't expected to be implemented directly.  However, if you* previously did implement it and are now getting errors* about missing <code>apply()</code>, you can simply call* {@link #commit} from <code>apply()</code>.*/
    void apply();
    

    如果在 UI 线程内操作并且不关心返回值,推荐使用方法 apply

    If you don’t care about the return value and you’re using this from your application’s main thread, consider using {@link #apply} instead.

清除共享首选项

获取 SharedPreferences.Editor 对象后,还可以调用其函数清除相对应的共享首选项:

    /*** Mark in the editor that a preference value should be removed, which* will be done in the actual preferences once {@link #commit} is* called.* * <p>Note that when committing back to the preferences, all removals* are done first, regardless of whether you called remove before* or after put methods on this editor.* * @param key The name of the preference to remove.* * @return Returns a reference to the same Editor object, so you can* chain put calls together.*/Editor remove(String key);

其返回一个新的 SharedPreferences.Editor 对象

如果想要全部清除可以调用函数 clear

    /*** Mark in the editor to remove <em>all</em> values from the* preferences.  Once commit is called, the only remaining preferences* will be any that you have defined in this editor.* * <p>Note that when committing back to the preferences, the clear* is done first, regardless of whether you called clear before* or after put methods on this editor.* * @return Returns a reference to the same Editor object, so you can* chain put calls together.*/Editor clear();

其同样返回一个新的 SharedPreferences.Editor 对象

Note:执行完清除动作后还需要进行提交操作,使用 apply 或者 commit 方法

读取共享首选项

获取 SharedPreferences 对象后,就可以调用函数进行读取

abstract Map<String, ?> getAll()
abstract boolean    getBoolean(String key, boolean defValue)
abstract float  getFloat(String key, float defValue)
abstract int    getInt(String key, int defValue)
abstract long   getLong(String key, long defValue)
abstract String getString(String key, String defValue)
abstract Set<String>    getStringSet(String key, Set<String> defValues)

调用函数 contains 可以判断是否存在该键值对:

/*** Checks whether the preferences contains a preference.* * @param key The name of the preference to check.* @return Returns true if the preference exists in the preferences,*         otherwise false.*/
boolean contains(String key);

接口

SharedPreferences 还包含了一个接口 SharedPreferences.OnSharedPreferenceChangeListener

/*** Interface definition for a callback to be invoked when a shared* preference is changed.*/
public interface OnSharedPreferenceChangeListener {/*** Called when a shared preference is changed, added, or removed. This* may be called even if a preference is set to its existing value.** <p>This callback will be run on your main thread.** @param sharedPreferences The {@link SharedPreferences} that received*            the change.* @param key The key of the preference that was changed, added, or*            removed.*/void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key);
}

SharedPreferences 对象调用函数 registerOnSharedPreferenceChangeListener 注册该接口后,当其 改变,增加或者移除 了某个键时,会调用该函数

示例:

public class MainActivity extends AppCompatActivity implements SharedPreferences.OnSharedPreferenceChangeListener {private static final String TAG = MainActivity.class.getSimpleName();@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);SharedPreferences sharedPreferences = getSharedPreferences("test", Context.MODE_PRIVATE);sharedPreferences.registerOnSharedPreferenceChangeListener(this);SharedPreferences.Editor editor = sharedPreferences.edit();editor.putString("key", "value");editor.commit();}@Overridepublic void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {Log.e(TAG, "onSharedPreferenceChanged: key = " + key);}
}

SharedPreferencesUtil.java

参考:消除unchecked cast Warning

封装 SharedPreferences 操作,方便日后使用

分为 4 个部分,构造函数,写入,删除,获取

可选择默认共享首选项文件,或者自定义共享首选项文件

完整代码如下:

import android.content.Context;
import android.content.SharedPreferences;import java.util.Set;/*** Created by zj on 2017/7/18.*/public class SharedPreferencesUtil {private static final String TAG = "SharedPreferencesUtil";// 获取 SharedPreferences 对象 --------------------------------private static SharedPreferences sharedPreferences;private static SharedPreferences getInstance(Context context) {if (sharedPreferences == null) {sharedPreferences = getSharedPreferences(context, TAG);}return sharedPreferences;}private static SharedPreferences getSharedPreferences(Context context, String name) {return context.getSharedPreferences(name, Context.MODE_PRIVATE);}// 写入 ---------------------------------------------------/*** 写入共享首选项,可写入 字符串 / 布尔值 / 整形 / 长整形 / 浮点型** @param context 上下文* @param key     键* @param value   值*/public static <T> void apply(Context context, String key, T value) {SharedPreferences sharedPreferences = getInstance(context);SharedPreferences.Editor editor = sharedPreferences.edit();if (value instanceof String) {editor.putString(key, String.valueOf(value));} else if (value instanceof Boolean) {editor.putBoolean(key, (Boolean) value);} else if (value instanceof Integer) {editor.putInt(key, (Integer) value);} else if (value instanceof Long) {editor.putLong(key, (Long) value);} else if (value instanceof Float) {editor.putFloat(key, (Float) value);}editor.apply();}/*** 写入共享首选项,可写入 字符串 / 布尔值 / 整形 / 长整形 / 浮点型** @param context 上下文* @param name    共享首选项文件名* @param key     键* @param value   值*/public static <T> void apply(Context context, String name, String key, T value) {SharedPreferences sharedPreferences = getSharedPreferences(context, name);SharedPreferences.Editor editor = sharedPreferences.edit();if (value instanceof String) {editor.putString(key, String.valueOf(value));} else if (value instanceof Boolean) {editor.putBoolean(key, (Boolean) value);} else if (value instanceof Integer) {editor.putInt(key, (Integer) value);} else if (value instanceof Long) {editor.putLong(key, (Long) value);} else if (value instanceof Float) {editor.putFloat(key, (Float) value);}editor.apply();}/*** 写入字符串集** @param context 上下文* @param key     键* @param values  值*/public static void applyStringSet(Context context, String key, Set<String> values) {SharedPreferences sharedPreferences = getInstance(context);SharedPreferences.Editor editor = sharedPreferences.edit();editor.putStringSet(key, values);editor.apply();}/*** 写入字符串集** @param context 上下文* @param name    共享首选项文件名* @param key     键* @param values  值*/public static void applyStringSet(Context context, String name, String key, Set<String> values) {SharedPreferences sharedPreferences = getSharedPreferences(context, name);SharedPreferences.Editor editor = sharedPreferences.edit();editor.putStringSet(key, values);editor.apply();}// 清除 ----------------------------------------------/*** 清除对应健值对** @param context 上下文* @param key     键*/public static void remove(Context context, String key) {SharedPreferences sharedPreferences = getInstance(context);SharedPreferences.Editor editor = sharedPreferences.edit();editor.remove(key);editor.apply();}/*** 清除对应健值对** @param context 上下文* @param name    共享首选项文件名* @param key     键*/public static void remove(Context context, String name, String key) {SharedPreferences sharedPreferences = getSharedPreferences(context, name);SharedPreferences.Editor editor = sharedPreferences.edit();editor.remove(key);editor.apply();}/*** 清空整个共享首选项文件** @param context 上下文*/public static void clear(Context context) {SharedPreferences sharedPreferences = getInstance(context);SharedPreferences.Editor editor = sharedPreferences.edit();editor.clear();editor.apply();}/*** 清空整个共享首选项文件** @param context 上下文* @param name    共享首选项文件名*/public static void clear(Context context, String name) {SharedPreferences sharedPreferences = getSharedPreferences(context, name);SharedPreferences.Editor editor = sharedPreferences.edit();editor.clear();editor.apply();}// 读取 --------------------------------------------/*** 读取共享首选项 ,可读取 字符串 / 布尔值 / 整形 / 长整形 / 浮点型** @param context  上下文* @param key      键* @param defValue 默认值* @return 值*/public static <T> T get(Context context, String key, T defValue) {SharedPreferences sharedPreferences = getInstance(context);T res = null;if (defValue instanceof String) {res = cast(sharedPreferences.getString(key, String.valueOf(defValue)));} else if (defValue instanceof Boolean) {res = cast(sharedPreferences.getBoolean(key, (Boolean) defValue));} else if (defValue instanceof Integer) {res = cast(sharedPreferences.getInt(key, (Integer) defValue));} else if (defValue instanceof Long) {res = cast(sharedPreferences.getLong(key, (Long) defValue));} else if (defValue instanceof Float) {res = cast(sharedPreferences.getFloat(key, (Float) defValue));}return res;}/*** 读取共享首选项 ,可读取 字符串 / 布尔值 / 整形 / 长整形 / 浮点型** @param context  上下文* @param name     共享首选项文件名* @param key      键* @param defValue 默认值* @return 值*/public static <T> T get(Context context, String name, String key, T defValue) {SharedPreferences sharedPreferences = getSharedPreferences(context, name);T res = null;if (defValue instanceof String) {res = cast(sharedPreferences.getString(key, String.valueOf(defValue)));} else if (defValue instanceof Boolean) {res = cast(sharedPreferences.getBoolean(key, (Boolean) defValue));} else if (defValue instanceof Integer) {res = cast(sharedPreferences.getInt(key, (Integer) defValue));} else if (defValue instanceof Long) {res = cast(sharedPreferences.getLong(key, (Long) defValue));} else if (defValue instanceof Float) {res = cast(sharedPreferences.getFloat(key, (Float) defValue));}return res;}/*** 读取字符串集** @param context   上下文* @param key       键* @param defValues 默认值* @return 值*/public static Set<String> getStringSet(Context context, String key, Set<String> defValues) {SharedPreferences sharedPreferences = getInstance(context);return sharedPreferences.getStringSet(key, defValues);}/*** 读取字符串集** @param context   上下文* @param name      共享首选项文件名* @param key       键* @param defValues 默认值* @return 值*/public static Set<String> getStringSet(Context context, String name, String key, Set<String> defValues) {SharedPreferences sharedPreferences = getSharedPreferences(context, name);return sharedPreferences.getStringSet(key, defValues);}// --------------------------------------------------------@SuppressWarnings("unchecked")private static <T> T cast(Object obj) {return (T) obj;}}

这篇关于Android 数据保存 - SharedPreferences的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1081605

相关文章

【服务器运维】MySQL数据存储至数据盘

查看磁盘及分区 [root@MySQL tmp]# fdisk -lDisk /dev/sda: 21.5 GB, 21474836480 bytes255 heads, 63 sectors/track, 2610 cylindersUnits = cylinders of 16065 * 512 = 8225280 bytesSector size (logical/physical)

Eclipse+ADT与Android Studio开发的区别

下文的EA指Eclipse+ADT,AS就是指Android Studio。 就编写界面布局来说AS可以边开发边预览(所见即所得,以及多个屏幕预览),这个优势比较大。AS运行时占的内存比EA的要小。AS创建项目时要创建gradle项目框架,so,创建项目时AS比较慢。android studio基于gradle构建项目,你无法同时集中管理和维护多个项目的源码,而eclipse ADT可以同时打开

android 免费短信验证功能

没有太复杂的使用的话,功能实现比较简单粗暴。 在www.mob.com网站中可以申请使用免费短信验证功能。 步骤: 1.注册登录。 2.选择“短信验证码SDK” 3.下载对应的sdk包,我这是选studio的。 4.从头像那进入后台并创建短信验证应用,获取到key跟secret 5.根据技术文档操作(initSDK方法写在setContentView上面) 6.关键:在有用到的Mo

android一键分享功能部分实现

为什么叫做部分实现呢,其实是我只实现一部分的分享。如新浪微博,那还有没去实现的是微信分享。还有一部分奇怪的问题:我QQ分享跟QQ空间的分享功能,我都没配置key那些都是原本集成就有的key也可以实现分享,谁清楚的麻烦详解下。 实现分享功能我们可以去www.mob.com这个网站集成。免费的,而且还有短信验证功能。等这分享研究完后就研究下短信验证功能。 开始实现步骤(新浪分享,以下是本人自己实现

Android我的二维码扫描功能发展史(完整)

最近在研究下二维码扫描功能,跟据从网上查阅的资料到自己勉强已实现扫描功能来一一介绍我的二维码扫描功能实现的发展历程: 首页通过网络搜索发现做android二维码扫描功能看去都是基于google的ZXing项目开发。 2、搜索怎么使用ZXing实现自己的二维码扫描:从网上下载ZXing-2.2.zip以及core-2.2-source.jar文件,分别解压两个文件。然后把.jar解压出来的整个c

android 带与不带logo的二维码生成

该代码基于ZXing项目,这个网上能下载得到。 定义的控件以及属性: public static final int SCAN_CODE = 1;private ImageView iv;private EditText et;private Button qr_btn,add_logo;private Bitmap logo,bitmap,bmp; //logo图标private st

Android多线程下载见解

通过for循环开启N个线程,这是多线程,但每次循环都new一个线程肯定很耗内存的。那可以改用线程池来。 就以我个人对多线程下载的理解是开启一个线程后: 1.通过HttpUrlConnection对象获取要下载文件的总长度 2.通过RandomAccessFile流对象在本地创建一个跟远程文件长度一样大小的空文件。 3.通过文件总长度/线程个数=得到每个线程大概要下载的量(线程块大小)。

SQL Server中,查询数据库中有多少个表,以及数据库其余类型数据统计查询

sqlserver查询数据库中有多少个表 sql server 数表:select count(1) from sysobjects where xtype='U'数视图:select count(1) from sysobjects where xtype='V'数存储过程select count(1) from sysobjects where xtype='P' SE

时间服务器中,适用于国内的 NTP 服务器地址,可用于时间同步或 Android 加速 GPS 定位

NTP 是什么?   NTP 是网络时间协议(Network Time Protocol),它用来同步网络设备【如计算机、手机】的时间的协议。 NTP 实现什么目的?   目的很简单,就是为了提供准确时间。因为我们的手表、设备等,经常会时间跑着跑着就有误差,或快或慢的少几秒,时间长了甚至误差过分钟。 NTP 服务器列表 最常见、熟知的就是 www.pool.ntp.org/zo

高仿精仿愤怒的小鸟android版游戏源码

这是一款很完美的高仿精仿愤怒的小鸟android版游戏源码,大家可以研究一下吧、 为了报复偷走鸟蛋的肥猪们,鸟儿以自己的身体为武器,仿佛炮弹一样去攻击肥猪们的堡垒。游戏是十分卡通的2D画面,看着愤怒的红色小鸟,奋不顾身的往绿色的肥猪的堡垒砸去,那种奇妙的感觉还真是令人感到很欢乐。而游戏的配乐同样充满了欢乐的感觉,轻松的节奏,欢快的风格。 源码下载