In contentresolver, the data sharing between Android applications shows how Android implements the application. Program And details how to obtain the data shared by other applications. Contentproviders stores and retrieves data, which can be accessed by all applications. This is the only way to share data between applications. So how can we expose application data? Before Article You know that contentresolver uses contentprovider to obtain data shared with other applications, so the interfaces of contentresolver and contentprovider should be similar. The contentprovider is responsible
- Organize application data;
- Provide data to other applications;
Contentresolver is responsible
- Obtains the data provided by contentprovider;
- Modify/Add/delete updated data;
contentprovider how does one provide data to the outside world? Android provides contentprovider. A program can expose its data completely by implementing an abstract interface of contentprovider, in addition, contentproviders exposes data in a way similar to tables in a database, that is, contentprovider is like a "Database ". The data provided by the outside world should be basically the same as the data obtained from the database, except that the URI is used to indicate the "Database" that the outside world needs to access ". As for how to identify which database is needed from the URI, this is what the android underlying layer needs to do. In brief analysis, contentprovider provides external data operation interfaces: query (Uri, string [], String, string [], string) insert (Uri, contentvalues) Update (Uri, contentvalues, String, string []) Delete (Uri, String, string []) these operations are basically the same as database operations. For details, see the detailed description in Android SQLite parsing. Uri: the D part of URI may contain a _ id, which should appear in the SQL statement and can appear in a special way, this requires us to pay extra attention to this special information when providing data. The recommended method for Android SDK is to include an ID in the provided data table field. During table creation, integer primary key autoincrement identifies this ID field. contentprovider How is data organized? organization data mainly includes data storage, Data Reading, and data exposure as a database. Data storage needs to select the appropriate storage structure based on the design requirements, the preferred database, of course, you can also select other local files, or even data on the network. When reading data, exposing data in the form of a database requires that no matter how the data is stored, the data must be accessed in the form of data. there may be two other issues that need attention.
- When was contentprovider created? who created it? Do I need to start this application to access the data shared by an application? This issue is not explicitly stated in the android SDK, but from the perspective of data sharing, contentprovider should be created when Android is started, otherwise data sharing will not be discussed. Therefore, the element must be clearly defined in androidmanifest. xml.
- multiple programs may access a contentprovider through contentresolver at the same time. Will it cause "dirty data" like a database "? This problem requires synchronization of database access, especially data writing, in androidmanifest. when defining contentprovider in XML, consider the value of the element Multiprocess attribute. On the other hand, Android provides the policychange () interface in contentresolver, when the data changes, other contentobserver will be notified. The observer mode should be used in this place. In contentresolver, there should be some interfaces similar to register and unregister.
Now, you have provided a comprehensive analysis of contentprovider. You can use either of the following methods to create contentprovider: create a contentprovider of your own or add your data to an existing contentprovider, provided that you have the same data type and the permission to write content providers. Go to the notepad instance provided in the android SDK sample.Source code! Android SQLiteAnalysis By: Mirage | in: Android Development 17 8 2009 Speaking of SQLite, C ++, Java programmers, and other non-mainstream programmers should have heard of it, which shows that it is very popular. SQLite is a lightweight, embedded, and relational database. It is currently used in iPhone, Android, and other mobile phone systems and is widely used by other companies, such as Adobe, for details about SQLite, visit its official website. Before learning Android SQLite, you must have a deep understanding of SQL statements (if you forget it, take this opportunity to review it ). As for the basic knowledge of creating databases and tables, we will not describe them in detail due to the limited space. This mainly describes four basic operations of the database: add (insert), delete (delete) query and update are the most important parts in learning Android SQLite. In addition to these four operations, we also need to note that the recordset of the query results is obtained ). Android SQLiteAnalysis With these basic concepts, let's learn about Android SQLite. The following is a summary from the android SDK: The first thing to note is the sqlitedatabase class, which is described in detail in the android SDK. Its main interfaces are as follows:
return value |
function prototype |
long |
insert (string table, string nullcolumnhack, contentvalues values) convenience method for inserting a row into the database. |
int |
Delete (string table, string whereclause, string [] whereargs) convenience method for deleting rows in the database. |
cursor |
query (string table, string [] columns, string selection, string [] selectionargs, string groupby, string having, string orderby, string limit) query the given table, returning a cursor over the result set. |
int |
Update (string table, contentvalues values, string whereclause, string [] whereargs) convenience method for updating rows in the database. |
Are you familiar with this? Yes, this is the four basic operations of the database: add, delete, query, and update ). I feel a lot easier. I will take a closer look at the parameters of these functions and find that many parameters are defined according to SQL statements, Example: Select * From p_employee where ID <> '000000' order by ID ASC Two additional data structures are required: contentvalues and cursor; Contentvalues is equivalent to map [(string key, integer value)] in C ++. Its main interfaces include put () and get (). The main purpose of the insert operation is to write the corresponding data items to the table according to the data segment of the table. It can be seen that contentvalues is mainly used to store the data segments of each table in the table and their corresponding values. Cursor Is the record set of the query result. From the characteristics of the record set, we can think of the operations that it contains: movefirst (), movelast (), movenext (), move (), islast (), getcolumns (), etc, it is also an abstract class [abstract class], and sqlitecursor is its specific implementation. For the sqlitedatabase class, other functions worth attention are: Create () and execsql (). For other functions, such as begintransaction () and endtransaction (), you only need to know more about Database Synchronization operations. Additional instructions Finally, it is worth mentioning that sqliteopenhelper, a good helper class, simplifies database operations. According to the instructions in the android SDK documentation, you can also inherit this class and rewrite its interface to perform database operations. sqliteopenhelper has the following main interfaces: After careful analysis, it is found that this class mainly creates a database and manages the database version. When the getwritabledatabase () or getreadabledatabase () method of this class is called in a program, if there is no database at the time, the android system will automatically create a data database. Other auxiliary instructions
-
- All database files are stored in the mobile phone/data/Package_name/Databases path. The most important thing is that in Android, the data of all application software (including files and databases) is private to the application software. If you need to share data in different applications, you must use contentprovider. A contentprovider class implements a set of standard method interfaces, so that other applications can save or read various data types of this contentprovider.
- to facilitate testing, how can I view the SQLite database content? Use the tool sqlite3.exe provided by the android SDK. This is a command line utility that lists the main Commands used: view the table structure sqlite3 "path ". dump
for example, G: \ Android-SDK-window \ tools> sqlite3 30m. db3. bump, the running structure is as follows: beggin transaction; Create Table [tmprogramm] ([Index] integer, [NID] integer, [nchannelid] integer, [strtitle] char (255), [dwduration] integer, [strthumbnail] char (1024), [strurl] char (255), [strpathname] char (255 ), [strauthor] char (255), [dwsize] integer, [State] integer, [percent] integer, [strconverted] char (255 ), [dwvideotype] integer, [dwdownloadedbytes] integer, [strtime] char (255), [strhttpversion] char (255), [struseragent] char (255 ), [strreferer] char (255); commit; This is the statement used to create a database View the sqlite3 "path" in the table ". schema you can download the database file 30m for the specific running result. db3, run it in the command line and you will see other help commands to query sqlite3. help
Summary For more information, see the example (moandroid.database.zip. AndroidData storage (Summary) By: Mirage | in: Android Development 25 8 2009 The first two articles: Android SQLite parsing and data sharing between Android applications explain in detail how to use the database to store information and how to use contentprovider to obtain data shared by other applications, now we will summarize the android data storage, and select an appropriate data storage method as needed in the future development process. Android provides five data storage methods:
- Use sharedpreferences to store data;
- File storage data;
- SQLite database stores data;
- Use contentprovider to store data;
- Network Storage data;
3 and 4 have been described in detail in the data sharing space between Android SQLite parsing and Android applications. I will not repeat the description here. I will introduce the other three methods in detail. Use Sharedpreferences Store Data First, describe the sharedpreferences storage method. It is a mechanism provided by Android to store some simple configuration information, such as the username and password of the login user. It uses the map data structure to store data, and stores data in key-value mode, which can be simply read and written. The specific example is as follows: Void readsharedpreferences () { String strname, strpassword; Sharedpreferences user = getsharedpreferences ("user_info", 0 ); Strname = user. getstring ("name ",""); Strpassword = user getstring ("password ",""); } Void writesharedpreferences (string strname, string strpassword) { Sharedpreferences user = getsharedpreferences ("user_info", 0 ); Uer. Edit (); User. putstring ("name", strname ); User. putstring ("password", strpassword ); User. Commit (); } The Data Reading and writing methods are very simple, but there are some differences when writing: First call edit () to make it edit, then you can modify the data, and finally use commit () submit the modified data. In fact, sharedpreferences stores data to the device in XML format, under/data/<package name>/shares_prefs in file explorer of ddms. The preceding data storage result is used as an example. After opening the file, you can see the user_info.xml file. After opening the file, you can see: <? XML version = "1.0" encoding = "UTF-8"?> <Map> <String name = "name"> moandroid </string> <String name = "password"> sharedpreferences </string> </Map> Sharedpreferences is restricted: it can only be used in the same package and cannot be used between different packages. File Storage Data The file storage method is a commonly used method. The method for reading/writing files in Android is exactly the same as that in Java for implementing I/O. It provides openfileinput () and openfileoutput () to read files on the device. Filterinputstream and filteroutputstream can be detailed in the Java Io package description: String fn = "moandroid. log "; Fileinputstream FCM = openfileinput (FN ); Fileoutputstream Fos = openfileoutput (FN, context. mode_private ); In addition, Android provides other functions for operation. Composition For more information, see the android SDK. Network Storage Data Network Storage Methods need to deal with Android Network data packets. For more information about Android Network data packets, see which packages are referenced by the android SDK ?. Summary In the above five storage methods, we will find a suitable data storage method based on the design objectives, performance requirements, and space requirements in the future development process. Data storage in Android is private and cannot be accessed by other applications unless the data shared by other applications is obtained through contentresolver. I. Introduction to SQLite On the Android platform, an embedded relational database-SQLite is integrated. sqlite3 supports null, integer, real (floating point number), text (string text), and blob (binary object) data types, although it supports only five types, sqlite3 actually accepts data types such as varchar (N), char (N), decimal (P, S, it is only converted to the corresponding five data types during operation or storage. The biggest feature of SQLite is that you can save any type of data to any field, regardless of the Data Type declared in this column. For example, you can store strings in integer fields, floating point numbers in Boolean fields, or date values in numeric fields. But there is one exception: the field defined as integer primary key can only store 64-bit integers. When saving data other than Integers to this field, an error will occur. In addition, when parsing the create table statement, SQLite ignores the data type information following the field name in the create table statement. Ii. curd of SQLite Android provides a class named sqlitedatabase, which encapsulates APIs for database operations. This class can be used to create, query, and update data) and delete operations (crud ). For sqlitedatabase learning, we should master the execsql () and rawquery () methods. The execsql () method can be used to execute SQL statements with changing behaviors such as insert, delete, update, and create table. The rawquery () method can be used to execute select statements. Sqlitedatabase also provides operation methods for adding, deleting, updating, and querying: insert (), delete (), update (), and query (). These methods are actually used by cainiao who are not familiar with SQL syntax. For programmers who are familiar with SQL syntax, execsql () and rawquery () are used directly () to add, delete, update, and query data. Iii. SQLite Transaction Management Use the begintransaction () method of sqlitedatabase to start a transaction. When the program executes the endtransaction () method, it checks whether the transaction flag is successful. If it is successful, the transaction is committed, otherwise, roll back the transaction. When an application needs to commit a transaction, it must use the settransactionsuccessful () method to set the transaction flag to successful before the program executes the endtransaction () method. If the settransactionsuccessful () method is not called, transactions are rolled back by default. Iii. create and update data tables using SQLite If the application uses the SQLite database, you need to create the database table structure used by the application and add some initialization records when using the software for the first time. In addition, when upgrading the software, you also need to update the data table structure. In the Android system, a class named sqliteopenhelper is provided for us to manage database versions. This class is an abstract class that must be inherited before it can be used. To manage database versions, the sqliteopenhelper class has two important methods: oncreate (sqlitedatabase dB) and onupgrade (sqlitedatabase dB, int oldversion, int newversion) When the getwritabledatabase () or getreadabledatabase () method of sqliteopenhelper is called to obtain the sqlitedatabase instance used to operate the database, if the database does not exist, the android system automatically generates a database and then calls oncreate () method. The oncreate () method is called only when the database is generated for the first time. In the oncreate () method, you can generate the database table structure and add the initialization data used by some applications. The onupgrade () method is called when the database version changes. The database version is controlled by the programmer. Assume that the current database version is 1, after modifying the structure of the database table, you need to upgrade the software to update the database table structure on your mobile phone, you can set the original database version to 2 (or another value) and update the table structure in the onupgrade () method. When the number of software version upgrades is large, you can use the onupgrade () method to determine based on the original number and target version number, and then update the table structure and data. Both the getwritabledatabase () and getreadabledatabase () methods can obtain a sqlitedatabase instance used to operate the database. However, the getwritabledatabase () method opens the database in read/write mode. Once the disk space of the database is full, the database can only read but cannot write data. If the getwritabledatabase () method is used, an error occurs. The getreadabledatabase () method first opens the database in read/write mode. If the disk space of the database is full, it will fail to be opened. When the opening fails, it will continue to attempt to open the database in read-only mode. |