| 方式 | 特点 |
|---|---|
| 文件存储 | openFileInput()和openFileOutput()进行存写 |
| SharedPreferences | 以XML格式进行存储 |
| SQLite | 运算快、占用资源少、支持基本的sql语法 |
| ContentProvider | 可用于应用之间的数据交互 |
| 网络存储 | 通过网络提供的存储空间来存储/获取数据信息 |
- FileOutputStream fos = openFileOutput(String filename,int mode);
- FileInputStream fis = openFileInput(String filename);
| mode | desc |
|---|---|
| Context.MODE_PRIVATE | 该文件为当前程序私有 |
| Context.MODE_APPEND | 该文件的内容可以追加 |
| Context.MODE_WORLD_READABLE | 该文件的内容可以被其他程序“读” |
| Context.MODEL_WORLD_WRITEABLE | 该文件的内容可以被其他程序“写” |
- //参考对象为内存:从内存输出即写入、输入到内存即读取
-
- // 1.写入数据到文件
- String fileName = "myfile.txt";
- String data = "Hello, World!";
- try {
- FileOutputStream fos = openFileOutput(fileName, Context.MODE_PRIVATE);
- fos.write(data.getBytes());
- fos.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
-
- // 2.从文件中读取数据
- try {
- FileInputStream fis = openFileInput(fileName);
- InputStreamReader isr = new InputStreamReader(fis);
- BufferedReader br = new BufferedReader(isr);
- StringBuilder sb = new StringBuilder();
- String line;
- while ((line = br.readLine()) != null) {
- sb.append(line);
- }
- fis.close();
- String savedData = sb.toString();
- } catch (IOException e) {
- e.printStackTrace();
- }
以XML方式的轻量级存储,适合存储少量的键值对数据,适用于简单的配置信息、用户偏好设置和应用程序状态等,比如登录的用户名。
- // 存储数据到 SharedPreferences
- SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs", Context.MODE_PRIVATE);
- SharedPreferences.Editor editor = sharedPreferences.edit();
- editor.putString("key", "value");
- editor.apply();
-
- // 从 SharedPreferences 中读取数据
- String savedValue = sharedPreferences.getString("key", "default value");
- // 1. 创建实现类extends SQLiteOpenHelper
- public class DBHelper extends SQLiteOpenHelper {
- private static final String DATABASE_NAME = "myDb.db";
- private static final int DATABASE_VERSION = 1;
- private Context context;
-
- public DBHelper(Context context) {
- super(context, DATABASE_NAME, null, DATABASE_VERSION);
- this.context = context;
- }
-
- @Override
- public void onCreate(SQLiteDatabase db) {
-
- }
-
-
- @Override
- public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
-
- }
-
- }
-
-
- // 2. 创建实现类对象,并调用相关方法实现CRUD
- DBHelper dbHelper = new DBHelper(context);
- SQLiteDatabase db = dbHelper.getWritableDatabase();
- Cursor cursor = db.rawQuery("SELECT * FROM myTable", null);
- while (cursor.moveToNext()){
- int id = cursor.getInt(cursor.getColumnIndexOrThrow("id"));
- ...
- }
- cursor.close();
-
SQLiteDatabase对象自身提供了一些CRUD方法,像表记录添加、修改,理应上需要我们传入多个字段(包括字段名和字段值),而为了解决这个问题就有了ContentValues对象,它允许我们给其增加多个键(字段名)、值(字段值);
所以当我们执行这个SQLiteDatabase对象的自身提供的添加或修改方法只用传入ContentValues即可。
可以参考下面代码例子:
- ContentValues values = new ContentValues();
- values.put("name", "John Doe");
- values.put("age", 30);
- values.put("email", "johndoe@example.com");
-
- // 插入数据到数据库
- long newRowId = db.insert("myTable", null, values);
至于ContentProvider和网络存储这两种存储方式只有结合具体的需求项目才能更好地学习,这里就不介绍了,需要学习的可以自己搜索相关文章具体学习。