前言 啦啦啦~大家好,又见面啦~ 本篇博文讲和大家一起完成一个需要注册、登录的备忘录的,一起学习 SharedPreferences 的基本使用,学习 Android 中常见的文件操作方法,复习 Android 界面编程。 直接进入正题~ 基础知识1.SharedPre ...
前言
啦啦啦~大家好,又见面啦~
本篇博文讲和大家一起完成一个需要注册、登录的备忘录的,一起学习 SharedPreferences 的基本使用,学习 Android 中常见的文件操作方法,复习 Android 界面编程。
直接进入正题~
基础知识
1.SharedPreferences 的使用
使用SharedPreferences储存用户名和密码,SharedPreferences是直接处理
(1) SharedPreferences 的读取
在 Android 中,用于获取 SharedPreferences 的接⼝是 getSharedPreferences(String, int) 函数。 两个参数的意义:
String: Desired preferences file. If a preferences file by this name does not exist, it will be created when you retrieve an editor.
int: Operating mode. Use 0 or MODE_PRIVATE for the default operation.
我们对 SharedPreferences 的读取操作是通过 getSharedPreferences(String, int) 函数返回的 SharedPreferences 对象的方法来完成的。查阅文档可以看到,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)
所有方法都需要传入一个 defValue 参数,在给定的 key 不存在时,SharedPreferences 会直接返回 这个默认值。
(2)SharedPreferences 的写入
所有对 SharedPreferences 的写入操作,都必须通过 SharedPreferences.edit() 函数返回的 Editor对象来完成。
举例:
Context context = getActivity();SharedPreferences sharedPref = context.getSharedPreferences("MY_PREFERENCE", Context.MODE_PRIVATE);// Alternatively, if you need just one shared preference file for your activity, you can use the getPreferences() method:// SharedPreferences sharedPref =getActivity().getPreferences(Context.MODE_PRIVATE);SharedPreferences.Editor editor = sharedPref.edit(); editor.putInt("KEY_SCORE", newHighScore); editor.commit();
海外公司注册、海外银行开户、跨境平台代入驻、VAT、EPR等知识和在线办理:https://www.xlkjsw.com
原标题:Android开发7:简单的数据存储(使用SharedPreferences)和文件操作
关键词:Android
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们:
admin#shaoqun.com
(#换成@)。