Getting Started with Android (ix) file storage with Sharedpreferences storage

Source: Internet
Author: User

Original link: http://www.orlion.ga/578/

The Android system offers three ways to simply implement data persistence, namely file storage, Sharedpreference storage, and database storage. Of course, in addition to these three ways, you can also save the data in the phone's SD card, but the use of files, sharedpreference or database to save the data will be

is simpler and more secure than storing data in an SD card

One, the file storage

1. Store data in a file

A Openfileoutput () method is provided in the context class that can be used to store data in the specified file. This method receives two parameters, the first parameter is the file name, the name is used when the document is created, note that the file name specified here can not contain the path, because all the files are stored by default to/data/data/<packagename>/files/ Directory. The second parameter is the mode of operation of the file, there are two main modes to choose from, Mode_private and Mode_append. Where mode_private is the default mode of operation, indicating that when the same file name is specified, the content written will overwrite the contents of the original file, and mode_append means that if the file already exists, it will append content to the file and create a new file if it does not exist. In fact, there are two other modes of operation of the file, Mode_world_readable and Mode_world_writeable, both of which allow other applications to read and write to the files in our program, but because these two modes are too dangerous, Vulnerable to application security vulnerabilities, now obsolete in Android 4.2 version

The Openfileoutput () method returns a FileOutputStream object that can be used to write data to a file using the Java stream. Here is the code example:

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. Reading data from a file

The context class also provides a Openfileinput () method for reading data from a file. This method is simpler than openfileoutput (), it takes only one parameter, that is, the name of the file to be read, and then the system automatically loads the file into the/data/data/<package name>/files/directory. and returns a FileInputStream object.

code example:

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 ();}

Second, sharedpreferences storage

Sharedpreferences is the use of key-value pairs to store data, Sharedpreferences also supports a number of different data type storage, if the stored data type is integer, then the data read is integral type, the stored data is a string, The data read is still a string.

1. Store the data in the Sharedpreferences

To use Sharedpreferences to store data, you first get to the Sharedpreferences object. Android mainly offers three ways to get Sharedpreferences objects

      1. The Getsharedpreferences () method in the context class

        This method receives two parameters, the first parameter specifies the name of the Sharedpreferences file, and if one does not exist, the sharedpreferences file is stored in the/data/data/<packagename>/ The Shared_prefs directory. The second parameter specifies the mode of operation, with two main modes, mode_private and mode_multi_process. Mode_private is the default mode of operation, and direct incoming) effect is the same, indicating that only the current application can read and write to this sharedpreferences file. Mode_multi_process is typically used to read and write to the same sharedpreferences file in multiple processes. Mode_world_readable and mode_world_writeable have been deprecated in the Android 4.2 version.

      2. The Getpreferences () method in the Activity class

        This method is similar to the Getsharedpreferences () method in the context, but it only receives an operation mode parameter, because using this method automatically takes the currently active class name as the sharedpreferences filename.

      3. The Getdefaultsharedpreferences () method in the Preferencemanager class

        This is a static method that receives a context parameter and automatically uses the current application's package name as a prefix to name the sharedpreferences file

Once you get the Sharedpreferences object, you can begin to store data in the Sharedpreferences file, with three main steps:

      1. Call the edit () method of the Sharedpreferences object to get a Sharedpreferences.editor object

      2. Add data to the Sharedpreferences.editor object, such as adding a Boolean type of data using the Putboolean () method, adding a string using putstring ().

      3. The Commint () method is called to commit the data that is added, thus completing the data store operation.

2. Reading data from the Sharedpreferences

A series of Get methods are provided in the Sharedpreferences object to read the stored data, and each get method corresponds to Sharedpreferences.

A put method in editor, such as reading a Boolean data using the Getboolean () method, reads a string using the GetString () method. These get methods receive two parameters, the first parameter is the key, the key used to pass in the stored data can get the corresponding value, the second parameter is the default value, that is, when the incoming key cannot find the corresponding value, the default value will be returned. Cases:

Sharedpreferences pref = getsharedpreferences ("Data", mode_private); String name = pref.getstring ("name", ""); int = Pref.getint ("Age", 0); Boolean sex = Pref.getboolean ("Sex", true); LOG.D ("Sharedpreferences", name); LOG.D ("Sharedpreferences", "age=" + age); LOG.D ("Sharedpreferences", "sex=" + Sex);

Getting Started with Android (ix) file storage with Sharedpreferences storage

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.