android 使用sharedPreferences保存用户设置的参数

本文介绍了如何使用SharedPreferences类来保存和检索应用程序中持久的键值对数据,包括如何通过Editor对象写入和读取数据,以及数据的保存形式和读取方式。示例代码展示了如何保存和读取用户的姓名和年龄数据,并解释了数据是如何以XML格式保存的。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

官方文档介绍:

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).

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; }


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值