The 6th chapter of data Storage program, detailed persistence technology

Source: Internet
Author: User

The 6th chapter of data Storage program, detailed persistence technology

All apps can be said to deal with the data, leaving the data they are nothing. So how do we store some key data at ordinary times?

1 Persistence Technology Brief

Data persistence means that the instantaneous data in memory is saved to the storage device, ensuring that the data is not lost even when the phone or computer shuts down. The data stored in memory is instantaneous, while the data stored in the storage device is persisted, and persistence provides a mechanism for transforming the data between the transient state and the persistent state .

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 is relatively simpler, and more than the data saved in the SD card will be more secure.

2 File storage

???? File storage is the most basic form of data storage in Android, it does not do any formatting of the stored content, all the data is stored intact in the file, so it is more suitable for storing some simple text data or binary data.

2.1 Storing data in a file

A Openfileoutput () method is provided in the context class that can be used to store data in the specified file.

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

BufferedWriter writer = new bufferedwriter (new outputstreamwriter (openfileoutput (" Data ", Context. mode_private )));

Writer. Write (data);

?

So let's create a practical example that uses Openfileoutput () to store data.

S1: Creating a EditText control in Activity_main.xml

S2: Saving data in Mainactivity.java using the Openfileoutput () method

S3: Run the project and view

?

2.2 Reading data from a file

???? The data is stored in a file, and a Openfileinput () method is provided in the context class for reading data from the file.

???? Example program:

????

3 Sharedpreferences Storage

Unlike file storage, sharedpreferences is stored in a key-value pair. That is, but to save or retrieve a data, you must provide both the key value of the data.

Also, sharedpreferences can hold data of different classes, and if it is an integer, then the integer is taken, and if it is a string string, it is also taken out.

The specific usage will be described in detail below.

3.1 Storing data in sharedpreferences

To save data using sharedpreferences, you must obtain sharedpreferences in your program. This object is available in three ways:

1) The Getsharedpreferences () method in the context class: This parameter will pass in two parameters, sharedpreferences file name and operation mode. If the file name that is passed in does not exist, it is in the/data/data/< packagename>/shared_prefs/directory; There are two modes of operation, Mode_private and Mode_multi_process. Mode_private means that only the current program can read the file, mode_multi_process is typically used by multiple processes to access the file. (MULTI many)

2) Getpreferences () method in activity class: Compared with the above method, this method accepts only one parameter, which is the parameter of the operation mode. The filename implicitly considers the class name of the current activity.

3) Getdefaultsharedpreferences () method in the Preferencemanager class: This is a static method, It accepts a context parameter. And by default uses the currently active package name as a prefix to name the sharedpreferences file

?

Once the Sharedpreferences object is obtained, the data can be stored to the sharedpreferences file. The stored steps are divided into three stages:

S1: Call the Edit () method of the Sharedpreferences object to get a Sharedprefences.editor object

S2: Add data to the editor object using the Putxxx () method of the Sharedprefences.editor object

S3: Call the Commit () method to commit and store the data

?

Example program:

Activity_main.xml

Mainactivity.java

?

Let's look at the actual effect:

In fact, he's storing it as an XML file.

3.2 reading data from sharedpreferences

Directly on the code to explain how to use:

S1: Create a New button in the Activity_main.xml file

S2: Write this button's click event in Mainactivity.java

3.3 Implement remember Password function

S1: Implementing a Lauout:Login.xml

????

S2: Create Loginactivity.java

S3: Registering Login.xml and activity_main.xml files in Androidmainfest.xml

S4: Running the program

4 SQLite Database Storage

There is a DB---sqlite database in the Android OS. How does the SQLite database in Android work?

4.1 Creating a Database

Android in order to allow us to more easily manage the database, dedicated to provide a sqliteopenhelper help class, the use of this class can be very simple to create and upgrade the database;

1) Sqliteopenhelper is an abstract class. If we want to use it, we need to create our own helper class to inherit it .

2) There are two abstract methods in Sqliteopenhelper, namely OnCreate () and Onupgrade (), we must rewrite these two methods in our helper class, and then implement the logic of creating and upgrading the database separately in these two methods.

3) There are two very important example methods in Sqliteopenhelper, Getreadabledatabase () and Getwritabledatabase (). Both of these methods can create or open an existing database ( open directly if the database already exists, otherwise create a new database ) and return an object that can read and write to the database

4) There are two construction methods in the Sqliteopenhelper that can be rewritten, usually using a less-than-a-parameter construction method. This construction method receives four parameters, the first parameter is the context, this has nothing to say, must have it to operate the database. The second parameter is the database name, which is the name specified here when the database is created. The third parameter allows us to return a custom cursor when querying the data, usually passing null. The fourth parameter represents the version number of the current database and can be used to perform an upgrade operation on the database. Once the instance of Sqliteopenhelper is built, the getreadabledatabase () or Getwritabledatabase () method is called to create the database, and the database file is stored in the/data/data/< The package name>/databases/directory. At this point, the overridden OnCreate () method is also executed, so there is usually some logic to create the table here.

?

Instance:

S1: Creating Inherit the Sqliteopenhelper implementation class Mydatabasehelper, and override the OnCreate () method

S2: called in Mainactivity.java getwritabledatabase () method

Verify that the database is generated under:

4.2 Upgrading the Database

Considering a situation, now that we have a database that records the details of each book, and now we need to add a table category where the user records the books, what should we do?

The statement that creates the category table is:

CREATE TABLE Category (

ID Integer PRIMARY Key autoincrement,

Category_name text,

Category_code integer)

Is this requirement not to add the above create statement directly in Mydatabasehelper.java and call it in the OnCreate () method?

Of course not!

???? In fact, there is no reason to create success is not difficult to think, because at this time The bookstore.db database already exists, and no matter how we click the Create Database button, the OnCreate () method in Mydatabasehelper will not be executed again, so the newly added table will not be created.

???? The solution is to modify the Onupgrade () method based on the above:

???? Note that this time in Mainactivity.java, the fourth parameter to be entered when invoking the Mydatabasehelper constructor is different:

????

?

4.3 Adding data

Meeting is about creating and upgrading databases

4.4 Updating data

?

4.5 Deleting data

?

4.6 Querying data

?

4.7 Using SQL to manipulate databases

?

5 Best Practices for SQLite databases

?

5.1 Using transactions

?

5.2 Best Practices for upgrading databases

?

6 Summary and comments

?

?

The 6th chapter of data Storage program, detailed persistence technology

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.