Getting started with Android (9) file storage and SharedPreferences storage,

Source: Internet
Author: User

Getting started with Android (9) file storage and SharedPreferences storage,

Link: http://www.orlion.ga/578/

The Android system provides three methods for simple data persistence, namely file storage, SharedPreference storage, and database storage. Of course, in addition to the three methods, you can also save the data in the SD card of your mobile phone. However, if you use files, SharedPreference, or databases to save the data

It is simpler and more secure than saving data on the SD card.

I. File Storage

1. store data in files

The Context class provides an openFileOutput () method to store data in a specified file. This method receives two parameters. The first parameter is the file name. This parameter is used when the file is created. Note that the specified file name cannot contain the path, because all files are stored in the/data/<packagename>/files/directory by default. The second parameter is the file operation mode. There are two modes available: MODE_PRIVATE and MODE_APPEND. MODE_PRIVATE is the default operation mode, indicating that when the same file name is specified, the written content will overwrite the content in the original file, MODE_APPEND indicates that if the file already exists, content will be appended to the file. If the file does not exist, a new file will be created. In fact, there are two file operation modes: MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE. These two modes allow other applications to perform read and write operations on the files in our program, however, because these two models are too dangerous, they can easily cause application security vulnerabilities and are now obsolete in Android 4.2.

The openFileOutput () method returns a FileOutputStream object. After obtaining this object, you can use Java stream to write data to the file. The following is a sample code:

public void save() {    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. read data from a file

The Context class also provides an openFileInput () method for reading data from files. This method is simpler than openFileOutput (). It only receives one parameter, that is, the file name to be read, then the system automatically loads the file in the/data/<package name>/files/directory and returns a FileInputStream object.

Sample Code:

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 (IOException e) {        e.printStackTrace();    } finally {        if (reader != null) {            try {                reader.close();            } catch (IOException e) {                e.printStackTrace();            }        }    }    return content.toString();}

 

Ii. SharedPreferences Storage

SharedPreferences uses key-value pairs to store data. SharedPreferences also supports storage of different data types. If the storage type is integer, the read data is also integer, the stored data is a string, and the read data is still a string.

1. store data in SharedPreferences

To use SharedPreferences to store data, you must first obtain the SharedPreferences object. Android provides three methods to obtain SharedPreferences objects.

    1. GetSharedPreferences () method in the Context class

      This method receives two parameters. The first parameter is used to specify the name of the SharedPreferences file. If it does not exist, create one. The SharedPreferences file is stored in the/data/<packagename>/shared_prefs directory. The second parameter is used to specify the operation mode. There are two modes: MODE_PRIVATE and MODE_MULTI_PROCESS. MODE_PRIVATE is the default operation mode, which has the same effect as direct input, indicating that only the current application can read and write the SharedPreferences file. MODE_MULTI_PROCESS is generally used for reading and writing the same SharedPreferences file in multiple processes. The MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE modes have been deprecated in Android 4.2.

    2. GetPreferences () method in Activity Class

      This method is similar to the getSharedPreferences () method in Context, but it only receives one operation mode parameter, because when using this method, the name of the currently active class is automatically used as the name of the SharedPreferences file.

    3. Getdefasharsharedpreferences () method in the PreferenceManager class

      This is a static method. It receives a Context parameter and automatically uses the package name of the current application as the prefix to name the SharedPreferences file.

 

After obtaining the SharedPreferences object, you can start to store data in the SharedPreferences file in three steps:

    1. Call the edit () method of the SharedPreferences object to obtain a SharedPreferences. Editor object.

    2. Add data to the SharedPreferences. Editor object. For example, to add a boolean data, use the putBoolean () method. To add a string, use putString ().

    3. Call the commint () method to submit the added data to complete the data storage operation.

 

2. read data from SharedPreferences

The SharedPreferences object provides a series of get methods for reading stored data. Each get method corresponds to SharedPreferences.

A put Method in Editor. For example, to read a boolean data, use the getBoolean () method. to read a string, use the getString () method. These get methods receive two parameters. The first parameter is the key, and the key used for data storage is used to obtain the corresponding value. The second parameter is the default value, it indicates the default value that will be returned when the input key cannot find the corresponding value. Example:

                                SharedPreferences pref = getSharedPreferences("data" , MODE_PRIVATE);String name = pref.getString("name" , "");int age = pref.getInt("age" , 0);Boolean sex = pref.getBoolean("sex", true);Log.d("SharedPreferences", name);Log.d("SharedPreferences", "age=" + age);Log.d("SharedPreferences", "sex=" + sex);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.