[android] sharedPreference入门
/********************2016年5月6日 更新**************************************/
知乎:Android 如何实现判断用户首次使用,比如首次使用时展示软件使用教程?
面条:
你需要的是SharedPreferences。
SharedPreferences可以在本地存储一些简单的数据。
首次进入的时候判断在本地存储的一个boolean值或者int值,例如叫做isFirstOpen。
/**************************************************************************/
为了保存带有特殊字符的数据到文件中,谷歌提供的SharedPreference(共享参数)。
通过Context对象的getSharedPreference(name,mode)方法得到SharedPreference对象,name参数是文件名称,mode参数是上一节的那些模式。
调用sp对象的edit()方法,得到Editor编辑器对象
调用Editor对象的putString(key,value)方法放入数据,很像Map集合
调用Editor对象的commit()方法提交一下,很像数据库的事务操作,保证数据同时提交成功
自动创建文件/data/data/包名/shared_prefs/文件名.xml
读取sp很简单,同样的获取SP对象,调用SP对象的getString(key,defaultValue),应用程序的配置信息都可以利用这个来保存。不同类型的值保存时,节点就是自身的类型。特殊字符会进行转义。
拷贝项目,修改完包名后一定要重新导一下R文件,上诉方法不会抛异常,函数定义成void无返回类型。
java代码:
/** * 保存用户名和方法的业务方法 * @param context 上下文 * @param username 用户名 * @param password 方法 * @return */ public static void saveUserInfo(Context context,String username,String password){ SharedPreferences sp=context.getSharedPreferences("config", Context.MODE_PRIVATE); Editor ed=sp.edit(); ed.putString("username", username); ed.putString("password", password); ed.commit(); }
//读取 SharedPreferences sp=getSharedPreferences("config", Context.MODE_PRIVATE); et_username.setText(sp.getString("username","")); et_password.setText(sp.getString("password",""));
相关文章
- [PHP] laravel框架注意bootstrap/cache
- [日常] 小白来装机基本概念BIOS与硬盘分区
- [小程序]微信小程序获取位置展示地图并标注信息
- [小程序]微信小程序获取input并发送网络请求
- [小程序]微信小程序登陆并获取用户信息
- [小程序] 支付宝小程序使用list时提示元素不存在
- Android平台GB28181设备接入端PTZ指令对接详解
- [javascript] 支付宝小程序网络GET请求
- [android] 与PHP的session进行交互demo
- [android] post请求接口demo测试代码
- [android] 练习使用ListView(三)
- [android] 练习使用ListView(二)
- [android] 练习使用ListView(一)
- [android] 练习viewpagerindicator的使用(二)
- [日常] 小白来装机基本概念BIOS与硬盘分区
- [android] 两种异步方式
- [android] 通过比对进行容器联动
- [android] 实现返回键操作思路
- [android] 标题部分管理
- [android] socket在手机上的应用