官方文档介绍:

Using Shared Preferences

TheSharedPreferencesclass provides a general framework that allows you to save and retrieve persistent key-value pairs of primitive data types. You can useSharedPreferencesto save any primitive data: booleans, floats, ints, longs, and strings. This data will persist across user sessions (even if your application is killed).

User Preferences

Shared preferences are not strictly for saving "user preferences," such as what ringtone a user has chosen. If you're interested in creating user preferences for your application, seePreferenceActivity, which provides an Activity framework for you to create user preferences, which will be automatically persisted (using shared preferences).

To get aSharedPreferencesobject for your application, use one of two methods:

  • getSharedPreferences()- Use this if you need multiple preferences files identified by name, which you specify with the first parameter.
  • getPreferences()- Use this if you need only one preferences file for your Activity. Because this will be the only preferences file for your Activity, you don't supply a name.

To write values:

  1. Calledit()to get aSharedPreferences.Editor.
  2. Add values with methods such asputBoolean()andputString().
  3. Commit the new values withcommit()

To read values, useSharedPreferencesmethods such asgetBoolean()andgetString().


a.示例程序:保存用户设置的数据

/** * 保存各项参数 * @param name 姓名 * @param age 年龄 */public void save(String name, int age) {SharedPreferences preferences = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);Editor edit = preferences.edit();edit.putString("name", name);edit.putInt("age", age);edit.commit();}

在保存之后,sharedPreferences将会把数据保存在 /data/data/<应用程序包名>/shared_pres/目录下,且使用xml方式保存数据

示例程序保存的数据是:

<?xml version='1.0' encoding='utf-8' standalone='yes' ?><map><int name="age" value="23" /><string name="name">g形成</string></map>


b.示例程序:从sharedPreferences中读取数据

/** * @return 返回参数设置数据 */public Map<String, String > getPreferences(){Map<String, String> params = new HashMap<String, String>();SharedPreferences sp = context.getSharedPreferences("preferences", Context.MODE_PRIVATE);params.put("name", sp.getString("name", ""));params.put("age", String.valueOf(sp.getInt("age", 0)));return params;}


更多相关文章

  1. SpringBoot 2.0 中 HikariCP 数据库连接池原理解析
  2. 一句话锁定MySQL数据占用元凶
  3. andriod之ContentProvider读取外部存储图片
  4. android获取网页数据的几种方式
  5. Android(安卓)SQLite数据库学习笔记
  6. Parcel了解
  7. 使用SmartRefreshLayout 给RecyclerView 添加反弹效果示例
  8. Android(安卓)定时到服务器取数据并刷新
  9. x、Android保存图片至相册原生代码

随机推荐

  1. Android(安卓)handler src track
  2. android Animation图片渐变动画 Demo
  3. android 各国语言对应的缩写
  4. Android(安卓)8.0 添加一个可以让phone进
  5. 小技巧-如何快速让子view'拥有进出退出动
  6. android下lcd显示的两个问题
  7. 解决 Linux/Ubuntu: adb shell insufficie
  8. Official Note of Android (important pa
  9. 不同Activity之间传递数据
  10. android蓝牙开发入门到精通3---服务端客