Data Storage in Android Development

1. File Storage

(1) Store data in a file

The Context class provides the openFileOutput() method, with the first parameter being the file name (not including paths, all files are saved to/data/data//files/) and the second parameter being the operation mode of the file, MODE_PRIVATE being the default mode, overwriting the contents of the file, and MODE_APPEND appending the contents of the file.

    * @param name The name of the file to open; can not contain path
    *             separators.
    * @param mode Operating mode.  Use 0 or {@link #MODE_PRIVATE} for the
    * default operation, {@link #MODE_APPEND} to append to an existing file,
    * {@link #MODE_WORLD_READABLE} and {@link #MODE_WORLD_WRITEABLE} to control
    * permissions.
    *
    * @return The resulting {@link FileOutputStream}.
    public abstract FileOutputStream openFileOutput(String name, int mode)
        throws FileNotFoundException;

This method returns a FileOutputStream object, which is used to build an OutputStream Writer that converts character streams into byte streams and has 8K of memory for conversion.

private ByteBuffer bytes = ByteBuffer.allocate(8192);

Then use BufferWriter to write the text content to the file.The object has an 8K buffer to reduce the cost of the sending process.

public BufferedWriter(Writer out) {
    this(out, 8192);
}

Send using the write method:

public void write(char[] buffer, int offset, int count) throws IOException

Example:

public void save() throws IOException {
    String data = "Data to save";
    FileOutputStream out = null;
    BufferedWriter writer = null;
    try {
        out = openFileOutput("data", Context.MODE_PRIVATE);
        writer = new BufferedWriter(new OutputStreamWriter(out));
        writer.write(data);
    }catch (IOException e){
        e.printStackTrace();
    }finally {
        try {
            if (writer != null) {
                writer.close();
            }
        }catch (IOException e){
                e.printStackTrace();
        }
    }
}

(2) Reading data from files

The Context class provides an openFileInput method for reading data from a file with only one parameter, the file name. The system will look for a file with the same name in the / data/data//files/file and return the FileInputStream object.

@Override
public FileInputStream openFileInput(String name)
    throws FileNotFoundException {
    return mBase.openFileInput(name);
}

Build an InputStreamReader object with the FileInputStream object, then build a BufferReader object, read the contents of the file line by line through the readline method, and store it in the StringBuffer object (it is more efficient to use StringBuffer when strings need to be manipulated frequently).

public  String load() {
    FileInputStream in = null;
    BufferedReader reader = null;
    StringBuilder content = new StringBuilder();
    try{
        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();
}

Note: Use of non-empty judgment on strings

if(TextUtils.isEmpty(Text)){}

You can tell that there are two null values, a null string and a zero string length.

public static boolean isEmpty(@Nullable CharSequence str) {
    if (str == null || str.length() == 0)
        return true;
    else
        return false;
}

2. SharedPreferences Storage

SharedPreferences are stored as key-value pairs.
There are three ways to get SharedPreferences:

  1. The getSharedPreferences() method of the Context class, the first parameter is the file name, and the second parameter is the operation mode.MODE_PRIVATE is the default mode, which has the same effect as Pass-0, allowing only the current application to read and write, and MODE_MULTI_PROCESS is used when multiple processes need to operate on it.

    @Override
    public SharedPreferences getSharedPreferences(String name, int mode) {
        return mBase.getSharedPreferences(name, mode);
    }
    
  2. The getPreferences() method in the Activity class accepts only the schema parameter, and the name uses the class name of the current activity.

    public SharedPreferences getPreferences(int mode) {
        return getSharedPreferences(getLocalClassName(), mode);
    }
    
  3. The getDaufltSharedPreferences() method in the PreferenceManager class accepts only the Context parameter and automatically names with the package name prefix.

    public static SharedPreferences getDefaultSharedPreferences(Context context) {
        return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
                getDefaultSharedPreferencesMode());
    }
    

Three steps of storage:

1. call SharedPreferences Object's edit Method, get a Edit Object;
2. Use putBoolean,putString Method Direction Edit Add data to the object;
3. Use commit()Method to submit, complete the data storage operation.

    SharedPreferences.Editor editor = getSharedPreferences("data",MODE_PRIVATE).edit();
    editor.putString("name","test");
    editor.commit();

Read data:
Steps are similar to storage in that they are replaced by getBoolean, getString, and so on.

3. SQLite database storage

//TODO database section

Keywords: Database SQLite

Added by dcampbell18 on Fri, 12 Jul 2019 19:51:43 +0300