Android保存数据的方式,有如下四种:
1、Shared Preferences:主要用于保存程序的系统配置信息。用来存储“key-values paires”。一般用于保存程序启动时设定的信息,以便在程序下一次启动时继续保留前一次设定的信息。
2、Files:用文件的形式保存信息。可以通过对文件的读写来获取或保存相关信息。
3、SQLite:用数据库的形式保存信息。SQLite是一个开源的数据库 系统。
4、NetWork:将数据保存于网络。
关键代码:
1、Shared Preferences
- /* ==================================
-
读取值
-
================================== */
-
// 取得活动的Preferences对象
-
SharedPreferences settings = getPreferences(Activity.MODE_PRIVATE);
-
-
// 取得值
-
value = settings.getBoolean("key", false);
-
-
/* ==================================
-
保存值
-
================================== */
-
// 取得活动的Preferences对象
-
SharedPreferences uiState = getPreferences(Activity.MODE_PRIVATE);
-
-
// 取得编辑对象
-
SharedPreferences.Editor editor = uiState.edit();
-
-
// 添加值
-
editor.putBoolean("key", value);
-
-
// 提交保存
-
editor.commit();
生成的文件放在:/data/data/XXX/shared_prefs/...
2、Files
- /* ===================================
-
读取值
-
================================== */
-
// 构建Properties对象
-
Properties properties = new Properties();
-
-
// 打开输入文件
-
FileInputStream stream = this.openFileInput("inputfile");
-
-
// 读取文件内容
-
properties.load(stream);
-
-
/* ===================================
-
保存值
-
================================== */
-
// 构建Properties对象
-
Properties properties = new Properties();
-
-
// 将数据打包成Properties
-
properties.put("key", "value");
-
-
// 打开输出文件
-
FileOutputStream stream = this.openFileOutput("outputfile", mode);
-
-
// 将打包好的数据写入文件
-
properties.store(stream, "");
阅读(978) | 评论(0) | 转发(0) |