Preface
Recently in the "first line of Android code" and "Crazy Android Handout", my feeling is that the essence of Android application is the data processing, including data reception, storage, processing and display, I would like to write a blog for these rings, remember my learning experience, Also hope to be with you novice classmates to promote each other. Today this blog, I would like to introduce the storage of data, because the data receiving, storage, processing and display of these rings interlocking, and the storage of data directly related to the processing and display of data, it is particularly important.
So this paper summarizes the common scheme of data storage and its usage. Divided into program storage and inter-program data access, in-program storage describes the file storage, sharedpreferences storage, database storage three different storage methods of the advantages and disadvantages and differences, using examples to explain the respective usage, highlighting the operation of database storage. Inter-Program data access describes the content provider.
Android in-app data storage solution:
The Android system offers three ways to simply implement data persistence, namely file storage, Sharedpreferences 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 using file storage, Sharedpreferences storage, and database storage will be more secure and simpler than saving the data on your phone's SD card [1].
First, the 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. If you want to use file storage to save some more complex text data, you need to define a set of your own formatting specifications, which makes it easier to re-parse the data from the file later. Because of the way the file storage has limitations, in the actual project is seldom used, we also do not specifically expand said.
second, sharedpreferences storage:
Unlike how files are stored, sharedpreference stores data in a way that uses key-value pairs. That is, when you save a piece of data, you need to give the data a corresponding key, so that when the data can be read by this key to the corresponding value to be taken out. And Sharedpreferences also supports many different types of data storage, which is the advantage of sharedpreference than file storage.
Three ways to get Sharedpreferences objects
- The Getsharedpreferences () method in the context class
Sharedpreferences pref = getsharedpreferences ("Data", mode_private);
The first parameter specifies the name of the Sharedpreferences file. The second parameter specifies the mode of operation, and Mode_private indicates that only the current application can read and write to the sharedpreferences mode_multi_ Process is typically used to read and write to the same sharedpreferences file in multiple processes.
- The Getpreferences () method in the Activity class
Similar to the Getsharedpreferences () method in the context class, but only one operation mode parameter is accepted
- The Getdefaultsharedpreferences () method in the Preferencemanager class
Sharedpreferences pref = preferencemanager.getdefaultsharedpreferences (this);
This is a static method that receives the context parameter.
Example: Read and write Data via sharedpreferences
Shareread = (Button) Findviewbyid (r.id.share_read), Sharewrite = (button) Findviewbyid (r.id.share_write);/** * pref = Preferencemanager.getdefaultsharedpreferences (this); */pref = getsharedpreferences ("Data", mode_private); editor = Pref.edit (); Sharewrite.setonclicklistener (new View.onclicklistener () { @Override public void OnClick (View v) { editor.putstring ("Write", "This is A String "); /* Data submission * /Editor.commit (); }); Shareread.setonclicklistener (New View.onclicklistener () { @Override public void OnClick (View v) { String str = pref.getstring ("write", null); Toast.maketext (Mainactivity.this, str, toast.length_long). Show (); }});
- Implementation of stored data (sharewrite)
1. Call the edit () method of the Sharedpreferences object to get a Sharedpreferences.editor object
2. Add data to the Sharedpreferences.editor object, using Putboolean, putstring and other methods
3. Call the Commint () method to submit the added data
- Get Data (Shareread) implementation
1. Get method using Sharedpreferences object directly
2. The Get method receives two parameters, the first one is the key, the second parameter is the default value, and when the incoming key is not large to the corresponding value, the default value is returned.
Compared with SQLite database, Sharedpreferences object is more convenient and concise than creating database, creating table, writing SQL statement and so on. But Sharedpreferences also has its own flaws, such as it can only store Boolean,int,float,long and string five of simple data types, such as it can not be conditional query and so on. So no matter how simple the sharedpreferences data store operation is, it can only be a supplement to the storage method, rather than a complete replacement for other data storage methods such as the SQLite database [2].
third, database storage
Create DATABASE: Sqlitedatabase. Execsql ()
public class Mydatabasehelper extends Sqliteopenhelper {/ * Create a student data table */public static final String Create_ STUDENT = "CREATE Table STUDENT (" + "ID integer primary key autoincrement," + "number integer," + "Name text, " +" major text) "; Private Context mycontext; Public Mydatabasehelper (Context context, String name, sqlitedatabase.cursorfactory Factory, int version) { Super (context, name, Factory, version); Mycontext = context; } @Override public void OnCreate (Sqlitedatabase db) {/ * CREATE DATABASE * /Db.execsql (create_student); } @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) { }}
Update database: Onupgrade ()
public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) { /*drop table if exists student: Discovery database already exists Stu Dent This table deletes the * /db.execsql ("drop table if exists student"); OnCreate (db);}
Add Data: Contentvalues.put (), Sqlitedatabase.insert ()
Mydatabasehelper dbhelper = new Mydatabasehelper (This, "student.db, NULL, 2"); Sqlitedatabase db = DBHelper. Getwritabledatabase (); Contentvalues values = new Contentvalues (), Values.put ("number", 123456), Values.put ("name", "Steve"), Values.put (" Major "," CS ");d B.insert (" student ", null, values);
Update data: Sqlitedatabase. Update ()
Delete data: Sqlitedatabase. Delete ()
Query data: Cursor = sqlitedatabase. Query (), Cursor.get ()
/* The fourth parameter accepts a string type, so turn 123456, convert to string */cursor Cursor = db.query ("student", NULL, "number =?", "123456", NULL, NULL, NULL);
Query table
Query () method parameters |
corresponding SQL section |
Describe |
Table |
From table_name |
Specify the indication of the query |
Columns |
Select Column1,column2 |
Specify the column name of the query |
Selection |
where column = value |
Specify the WHERE constraint |
Selectionargs |
- |
Provide a specific value for a placeholder in the where |
GroupBy |
Group BY column |
Specify columns that require GROUP by |
Having |
Having column = value |
Further constraints on GROUP by results |
By |
Order by Column1, Column2 |
Specify how query results are sorted |
- using transactions: Transactions the characteristics can guarantee let a certain Series the operating Either it's done or it's not done.
The sqlitedatabase contains two methods to control transactions:
Start transaction: BeginTransaction ()
End transaction: Endtransaction ()
Whether in transaction: Intransaction ()
SET TRANSACTION flags: set Transactionsuccessful ()
If the program calls the method in the transaction execution to set the transaction to be successful, the transaction is committed, or the program rolls back the transaction
Attention:
Database view, we can enter the Sdk/platform-tools through the command line, enter the ADB shell, you can input the basic instructions of the database. But I think this way is not very convenient, my approach is to login to the SQLite Expert official website (http://www.sqliteexpert.com/download.html) Download a sqlite expert Personal 3, the personal version is free of charge. Then you can enter Android Monitor Device in Android Studio or Eclipse, find the data/data/package name/database/*.db in the File Explorer, click Export, Then you can open it with this software.
data content provider between Android programs:
The above three scenarios are a single program of data storage, and we in some scenarios, we need to use the system application of data, such as the use of the system's address book, SMS and Media Library and other functions, which requires us to use the content provider (Provider), It can be used to share data between different applications.
I. Obtaining data from other applications
The content provider accesses the data that is shared in the content provider through the Contentresolver class, Contentresolver is obtained by Context.getcontentresolver ().
cursor cursor = getcontentresolver (). Query ( URI, projection, selection, Selectionargs, SortOrder);
Query table
Query () method parameters |
corresponding SQL section |
Describe |
Uri |
From table_name |
Specify the indication of the query |
Projection |
where column = value |
Specify the WHERE constraint |
Selection |
- |
Provide a specific value for a placeholder in the where |
Selectionargs |
Group BY column |
Specify columns that require GROUP by |
By |
Order by Column1, Column2 |
Specify how query results are sorted |
In this case, we will find that the content provider query method is similar to the database, using the query () method, except that the arguments passed into the query () method are different. The content provider passes in the value of the query contains the URI, and the URI records the address of the target data, and the database into query contains the table name, because the database is the operation of its own program file directory, so it does not need to locate, and the content provider first to locate the program's package name, In order to locate the Data folder, finally to the table name, in the URI, we can see the last slash followed by the table name.
standard format for URIs
content://com.example.app.provider/table
parsing of URIs
uri uri = uri.parse ("content://com.example.app.provider/table")
URI Rules
* denotes any character that matches any length
content://com.example.app.provider/*
# indicates matching numbers of any length
content://com.example.app.provider/table/#
Second, provide the application of their own data
- Six ways to content providers
1, OnCreate ()
Initializes the content provider. The creation and upgrade of the database is completed and only the Contentresolver attempts to access the program data will be initialized.
2. Query ()
Query data. URI determines which table to check, projection query columns, selection, and Selectionargs queries which rows
3. Insert ()
Add data
4. Update ()
Update data that is already in the content provider
5. Delete ()
Delete data
6, GetType ()
Returns the corresponding MIME type based on the content URI passed in.
A content URI corresponds to a mime string as long as there are three components
(1) must start with VND
(2) End with path, followed by android.cursor.dir/, end with ID, followed by android.cursor.item/
(3) Finally, connect the vnd.<authority>.<path>
Urimatcher class
Adduri () method, which takes three parameters, and passes the permissions, path, and a custom code
The match () method, which passes the URI object in, and the return value is a custom code that matches the URI object that corresponds to the
The core of the content-providing class is to locate the data through the URI object, but after the data is positioned successfully, it can be read in a way similar to the database operation. If you want to share your own data, you can also use the URI object to throw your own location, waiting for other programs to locate themselves to get the data
Summary:
Storage mode |
Use |
Characteristics |
File storage |
Store some simple text data or binary data |
Do not format any of the stored content |
Sharedpreferences Storage |
Storage of Boolean,int,float,long and string five simple data types with small data volumes |
Convenient, concise, using key-value pairs to store data, support a variety of different data type storage, but not conditional query |
Database storage |
Large data volumes and conditions |
Powerful, conditional query, data additions and deletions, but the use of more complex |
Content providers |
Data exchange across Programs |
To locate a data source by using a URI object |
[1] Guo Lin. First line of code ANDROID[J]. 2014.
[2] big weather. Four ways to store Android. http://www.cnblogs.com/greatverve/archive/2011/12/27/ Android-sharedpreference-file-sqlite-contentprovider.html
Android Learning: Data storage solution Induction and summary