Data Storage Full Solution--Detailed Persistence Technology

Persistence technology provides a mechanism to convert data between transient and persistent states.

The data persistence technologies in Android mainly include:
1. File storage
2. SharedPreference storage
3. Database storage

1 file storage

There is no formatting of the stored content, and all data is kept intact in the file.

Suitable for scenarios:
1. Store some simple text data and binary data

1.1 Storing data in a file

The Context class provides the openFileOutput() method, which can be used to store data in the specified file and return a FileOutputStream object. After obtaining this object, the data can be written to the file in the form of Java streams.

public void save(String inputText){
    FileOutputStream out = null;
    BufferedWriter writer = null;
    try {
        /**
         * Java流操作:
         * 通过openFileOutput()方法得到一个FileOutputStream对象,
         * 然后借助与它构建一个OutputStreamWriter对象,
         * 然后使用它构建BufferedWriter对象,这样就可以借助BufferWriter对象将文本内容写入文本
         */

        /**
         * 第一个参数是文件名,第二个参数是文件操作模式,
         * 注意:这里指定的文件名不包含路径,所有文件都默认存储到/data/data/<package name>/files/目录下
         * 支持两种操作模式:1.MODE_PRIVATE是默认操作模式,表示同一个文件保存时会覆盖原来的内容,
         *                2.MODE_APPEND,表示同一个文件保存时会在问价末尾追加内容
         */
        out = openFileOutput("data", Context.MODE_PRIVATE);
        writer = new BufferedWriter(new OutputStreamWriter(out));
        writer.write(inputText);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            if(writer!=null){
                writer.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1.2 Reading data from a file

The openFileInput() method is also provided in the Context class for reading data from a file.

public String load(){
    FileInputStream in = null;
    BufferedReader reader = null;
    StringBuilder content = new StringBuilder();
    try {
        /**
         * 先通过openFileInput()方法获取一个FileInputStream对象,
         * 然后借助它构建一个InputStreamReader对象,
         * 然后借助它构建一个BufferReader对象,
         * 这样我们就可以通过BufferReader对象进行一行一行的读取,并保存在StringBuilder对象中
         */

        /**
         * 只接收一个参数,即要读取的文件名,
         * 系统会自动到/data/data/<package name>/files/目录下去加载这个文件,
         * 返回一个FileInputStream对象,
         * 之后就可以通过Java流的方式将数据读取出来
         */
        in = openFileInput("data");
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while((line = reader.readLine())!=null){
            content.append(line);
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(reader!=null){
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return content.toString();
}

2 SharedPreferences storage

SharedPreferences uses key-value pair classes to save data. SharedPreferences supports multiple types of data storage, so using SharedPreferences classes for data persistence is much more convenient than using files.

2.1 Store data in SharedPreferences

First of all, to get the SharedPreferences object, there are 3 methods:
1) The getSharedPreferences() method in the Context class

/**
 * context:Context类型
 * 接收两个参数,
 * 参数一:SharedPreferences 文件名称,
 * SharedPreferences 文件都存放在 /data/data/<package name>/shared_prefs/ 目录下,
 * 参数二:指定操作模式,
 * 有唯一一个操作模式:MODE_PRIVATE,与传入0效果相同,表示只有当前的应用程序才可以对这个 SharedPreferences 文件进行操作
 */
SharedPreferences sp = context.getSharedPreferences(Constants.PREFERENCE_NAME, Context.MODE_PRIVATE);

2) getPreferences() method in Activity class

/**
 * 用法与Context 中的getSharedPreferences() 方法类似,
 * 只有一个参数:MODE_PRIVATE,
 * 会自动将当前活动的类名作为SharedPerferences 的文件名
 */
SharedPreferences sp = this.getPreferences(MODE_PRIVATE);

3) getDefaultSharedPreferences() method in PreferencesManager class

/**
 * 静态方法,
 * 只有一个参数:Context,
 * 自动使用当前应用程序的包名作为前缀来命名 SharedPreferences 文件
 */
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);

After getting the SharedPreferences object, you can start storing data in the SharedPreferences file

/**
 * 调用 SharedPreferences 对象的 edit() 方法来获取一个 SharedPreferences.Editor 对象
  */
SharedPreferences.Editor editor = sp.edit();
/**
 * 向 SharedPreferences.Editor 对象中添加数据,
 * 可以是多种数据类型
 */
editor.putBoolean("name",true);
editor.putFloat("name",1.0f);
editor.putInt("name",1);
editor.putLong("name",1);
editor.putString("name","value");
HashSet<String> value = new HashSet<>();
value.add("value");
editor.putStringSet("name",value);
/**
 * 调用 apply() 方法将添加的数据提交
 */
editor.apply();

2.2 Reading data from SharedPreferences

/**
 * SharedPreferences 对象中提供了一系列 get 方法,用于对存储的数据进行读取,
 * 每种 get 方法都对应了 SharedPreferences.Editor 中的一种 put 方法,
 * 这些 get 方法都有两个参数,
 * 参数一:键
 * 参数二:默认值,
 * 当传入的键找不到对应的值时,使用默认值
 */
boolean rl = sp.getBoolean("name",false);
float r2 = sp.getFloat("name",0.0f);
int r3 = sp.getInt("name",0);
long r4 = sp.getLong("name",0);
String r5 = sp.getString("name","");
HashSet<String> value1 = new HashSet<>();
HashSet<String> r6 = (HashSet<String>) sp.getStringSet("name",value1);

2.3 SharedPreferences tool class

SharedPreferences utility class

3 SQLite database storage

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326392277&siteId=291194637