Preface
Android
There are 5 commonly used data storage methods:SharePreferences
SQLite database, file storage,ContentProvider
& network storage
table of Contents
1 Introduction
- Definition: a data storage method
- Essence: stored in xml in the form of key-value pairs
- Features: Lightweight
- Application scenario: Lightweight storage (such as application configuration, parameter attributes)
- Default storage path:
/data/data/<PackageName>/shared_prefs
2. Contrast
In addition SharedPreferences
, Android
common data storage methods mainly include:
- SQLite database
- File storage
- ContentProvider
- Network Storage
The details are as follows:
3. Specific use
For SharePreferences
the use, it mainly includes saving data & reading data.
3.1 Save data
- Essence: stored in the xml file in the form of key-value pairs
- The files are stored in the /data/data//shared_prefs directory
- The use steps are as follows:
// 步骤1
SharedPreferences sharedPreferences =getSharedPreferences("mltest", Context.MODE_PRIVATE);
// 参数1:指定该文件的名称,名称不用带后缀,后缀会由Android自动加上
// 参数2:指定文件的操作模式,共有4种操作模式,分别是:
// Context.MODE_PRIVATE = 0:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
// Context.MODE_APPEND = 32768:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
// Context.MODE_WORLD_READABLE = 1:表示当前文件可以被其他应用读取
// Context.MODE_WORLD_WRITEABLE = 2:表示当前文件可以被其他应用写入
// 步骤2:通过Editor获取编辑器对象
Editor editor = sharedPreferences.edit();
// 步骤3:以键值对的方式写入数据
editor.putString("name", "四种模式");
editor.putInt("age", 4);
// 步骤4:提交修改
editor.commit();
3.2 Read data
// 步骤1
SharedPreferences sharedPreferences = getSharedPreferences("ljq", Context.MODE_PRIVATE);
// 参数1:指定该文件的名称,名称不用带后缀,后缀会由Android自动加上
// 参数2:指定文件的操作模式,共有4种操作模式,分别是:
// Context.MODE_PRIVATE = 0:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容
// Context.MODE_APPEND = 32768:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。
// Context.MODE_WORLD_READABLE = 1:表示当前文件可以被其他应用读取
// Context.MODE_WORLD_WRITEABLE = 2:表示当前文件可以被其他应用写入
// 步骤2
String name = sharedPreferences.getString("name", "");
int age = sharedPreferences.getInt("age", 1);
// getxxx():xxx为获取数据的数据类型
// 参数1:要获取的key
// 参数2:缺省值,即preference中不存在该key时返回默认值