原文地址:https://developer.android.com/training/basics/data-storage/shared-preferences.html

-------------------------------------------------------------------------------------------------------------------------------

If you have a relatively small collection of key-values that you'd like to save, you should use theSharedPreferences APIs. ASharedPreferences object points to a file containing key-value pairs and provides simple methods to read and write them. EachSharedPreferences file is managed by the framework and can be private or shared.

如果你有一个相对较小的键-值对集合想要存储,你应该使用SharedPreferences APIs。一个SharedPreferences对象指向一个包含键值对的文件,并且提供了一些简单的方法来进行读取和写入它们。每个SharedPreferences文件可以是私有的或是共享的,靠framework来管理它们。

This class shows you how to use the SharedPreferences APIs to store and retrieve simple values.

这节课演示如何使用SharedPreferences APIs来存储和检索简单的值。

Note: The SharedPreferences APIs are only for reading and writing key-value pairs and you should not confuse them with thePreference APIs, which help you build a user interface for your app settings (although they useSharedPreferences as their implementation to save the app settings). For information about using thePreference APIs, see theSettings guide.

注意:SharedPreferences APIs不仅仅可以读取和写入键值对,而且你不应该把它们和Preference APIs相混淆,后者帮助你为你的app设置建立一个用户接口(尽管在存储app设置时它们使用SharedPreferences实现)。

Get a Handle to a SharedPreferences ——得到一个SharedPreferences的句柄


You can create a new shared preference file or access an existing one by calling one of two methods:

  • getSharedPreferences() — Use this if you need multiple shared preference files identified by name, which you specify with the first parameter. You can call this from anyContext in your app.
  • getPreferences() — Use this from anActivity if you need to use only one shared preference file for the activity. Because this retrieves a default shared preference file that belongs to the activity, you don't need to supply a name.

你可以通过调用下面两个方法之一创建一个新的共享引用文件或进入一个已经存在的文件:

  • getSharedPreferences()——如果你需要多个 依靠名字(第一个参数)定义的共享引用文件,你可以使用这个函数。你可以从你的app中的任意Context里调用它。
  • getPreferences()——如果你在这个activity中仅仅需要使用一个共享应用文件,就使用这个方法。因为它检索一个属于这个activity的默认共享应用文件,你不需要提供一个名称。

For example, the following code is executed inside a Fragment. It accesses the shared preferences file that's identified by the resource stringR.string.preference_file_key and opens it using the private mode so the file is accessible by only your app.

例如,下面的代码在一个Fragment中执行。它依靠资源字符R.string.preference_file_key定义来访问一个共享应用文件,然后使用私有模式打开它,以使文件仅仅对你的app是可访问的。

Context context = getActivity();
SharedPreferences sharedPref = context.getSharedPreferences(getString(R.string.preference_file_key), Context.MODE_PRIVATE);

When naming your shared preference files, you should use a name that's uniquely identifiable to your app, such as"com.example.myapp.PREFERENCE_FILE_KEY"

Alternatively, if you need just one shared preference file for your activity, you can use thegetPreferences() method:

当给你的共享引用文件命名时,你应该使用一个唯一的、可确认的名字,例如“com.example.myapp.PREFERENCE_FILE_KEY”。或者,如果你仅仅需要一个共享引用文件,你可以使用getPreferences()方法。

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);

Caution: If you create a shared preferences file withMODE_WORLD_READABLE orMODE_WORLD_WRITEABLE, then any other apps that know the file identifier can access your data.

警告:如果你使用MODE_WORLD_READABLE 或者MODE_WORLD_WRITEABLE ,那么其他任何apps都知道这个文件标识符可以访问你的数据。

Write to Shared Preferences —— 向共享引用写入数据


To write to a shared preferences file, create a SharedPreferences.Editor by callingedit() on yourSharedPreferences.

为了向一个共享的应用文件写入,通过在你的SharedPreferences调用edit() 来创建一个SharedPreferences.Editor。

Pass the keys and values you want to write with methods such as putInt() andputString(). Then callcommit() to save the changes. For example:

利用putInt() 和putString()这样的方法传递你想要写入的键和值。然后调用commit()来存储变化。例如:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putInt(getString(R.string.saved_high_score), newHighScore);
editor.commit();

Read from Shared Preferences —— 从共享引用中读取数据


To retrieve values from a shared preferences file, call methods such as getInt() andgetString(), providing the key for the value you want, and optionally a default value to return if the key isn't present. For example:

为了从一个共享引用文件中检索数值,调用getInt() andgetString()等方法,提供一个你想到得到的键,和一个供选择的默认返回值(如果这个键不存在的话)。例如:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
int defaultValue = getResources().getInteger(R.string.saved_high_score_default);
long highScore = sharedPref.getInt(getString(R.string.saved_high_score), defaultValue);

转载于:https://www.cnblogs.com/xiaowangba/archive/2013/02/04/6314740.html

[Andriod官方训练教程]保存数据之保存键-值对的集合相关推荐

  1. python缺失值与异常值处理_pandas学习(常用数学统计方法总结、读取或保存数据、缺省值和异常值处理)...

    pandas学习(常用数学统计方法总结.读取或保存数据.缺省值和异常值处理) 目录 常用数学统计方法总结 读取或保存数据 缺省值和异常值处理 常用数学统计方法总结 count 计算非NA值的数量 de ...

  2. SortedDictionaryTKey, TValue 类 表示根据键进行排序的键/值对的集合。

    SortedDictionary<TKey, TValue> 类   表示根据键进行排序的键/值对的集合. SortedDictionary<TKey, TValue> 中的每 ...

  3. 给定key值,在Binary Search Tree中查找最接近该键值的结点集合

    http://blog.csdn.net/zhouhao011280s/article/details/8044056 给定key值,在Binary Search Tree中查找最接近该键值的结点集合 ...

  4. 使用sqlite保存数据返回主键

    /// <summary>/// 返回insert后的主键值/// </summary>/// <param name="SQLString"> ...

  5. APP如何保存数据?——iOS保存数据的4种方式

    在iOS开发过程中,不管是做什么应用,都会碰到数据保存的问题.将数据保存到本地,能够让程序的运行更加流畅,不会出现让人厌恶的菊花形状,使得用户体验更好.下面介绍一下数据保存的方式: 1.NSKeyed ...

  6. Android官方开发文档Training系列课程中文版:数据存储之键值对序列存储

    原文地址:http://android.xsoftlab.net/training/basics/data-storage/index.html 引言 大多数的安卓APP需要保存数据,即使仅仅存储在o ...

  7. TypeError: keys must be str, int, float, bool or None, not tuple,解决 python 中 json 保存不了字典键值为 元组 的问题

    >>> a = {('0xFFFA', 11): 32, ('0x00F3', 1): 1, ('0xFFFA', 2): 42} {('0xFFFA', 1): 32, ('0x0 ...

  8. python保存数据_Python 保存数据的方法(4种方法)

    Python 保存数据的方法: open函数保存 使用with open()新建对象 写入数据(这里使用的是爬取豆瓣读书中一本书的豆瓣短评作为例子) import requests from lxml ...

  9. 3、JavaWeb中Service层的作用、MyBatis的重要组件、mybatis-config.xml中的别名映射、properties配置、#{}和${}的区别、获取插入数据的主键值

    文章目录 1.Service层的作用 2.MyBatis重要组件 Resources SqlSessionFactoryBuilder SqlSessionFactory SqlSession 针对上 ...

最新文章

  1. 什么是javadoc文档
  2. 《团队——科学计算器代码设计规范》
  3. JZOJ 5414. 【NOIP2017提高A组集训10.22】幸运值
  4. idea安装行号快速定位行快捷键以及设置方法
  5. 前缀 中缀 后缀表达式
  6. ASP.NET服务器控件开发(2)--继承WebControl类
  7. python scrapy request_Scrapy中的Request和日志分析|python基础教程|python入门|python教程...
  8. Python-条件控制及循环
  9. 【转】【Linux】Linux下统计当前文件夹下的文件个数、目录个数
  10. [转]EXCEL截取字符串中某几位的函数——LeftMIDRight及Find函数的使用
  11. java表达式的类型_java – 此表达式的目标类型必须是功能界面
  12. php代码连接mysql数据库,php连接mysql数据库代码
  13. 推荐:绝对是最好用的公式编辑器
  14. 金万维异速联服务器重装,金万维异速联服务器配置说明
  15. 单项选择题标准化考试系统设计c语言版
  16. 数据不符合正态分布怎么处理呢
  17. NE 和 KE 堆栈脚本解析
  18. 遥感建筑物提取数据集
  19. 原声大碟 -《仙剑奇侠传三·电视原声带》[MP3]
  20. HTML表格(二)---成绩单

热门文章

  1. Uncontrolled memory mapping in camera driver (CVE-2013-2595)
  2. mysql 和 sqlserver sql差异比较
  3. security和oauth2.0的整合
  4. 《JAVA与模式》之桥梁模式
  5. BZOJ 3039: 玉蟾宫( 悬线法 )
  6. jquery Ajax请求本地json
  7. 洛谷 - P1217 - 回文质数 - 枚举
  8. 个人作业——福大微信公众号使用评测
  9. 两个Python web框架:Django Tornado比较
  10. Python学习(七)面向对象 ——封装