ContentProvider官方教程(3)ContentResolver查询、遍历 示例

Retrieving Data from the Provider

This section describes how to retrieve data from a provider, using the User Dictionary Provider as an example. 
For the sake of clarity, the code snippets in this section call ContentResolver.query() on the "UI thread"". In actual code, however, you should do queries asynchronously on a separate thread. One way to do this is to use the CursorLoader class, which is described in more detail in the Loaders guide. Also, the lines of code are snippets only; they don't show a complete application. 

  To retrieve data from a provider, follow these basic steps:

  • Request the read access permission for the provider.
  • Define the code that sends a query to the provider.

Requesting read access permission 第1步:声明权限

  To retrieve data from a provider, your application needs "read access permission" for the provider. You can't request this permission at run-time; instead, you have to specify that you need this permission in your manifest, using the <uses-permission> element and the exact permission name defined by the provider. When you specify this element in your manifest, you are in effect "requesting" this permission for your application. When users install your application, they implicitly grant this request. 

  要访问provier内的数据,必需先声明相应权限。

  To find the exact name of the read access permission for the provider you're using, as well as the names for other access permissions used by the provider, look in the provider's documentation. 
  The role of permissions in accessing providers is described in more detail in the section Content Provider Permissions. 
  The User Dictionary Provider defines the permission android.permission.READ_USER_DICTIONARY in its manifest file, so an application that wants to read from the provider must request this permission.

Constructing the query 第2步:构造查询语句

  The next step in retrieving data from a provider is to construct a query. This first snippet defines some variables for accessing the User Dictionary Provider: 

 1 // A "projection" defines the columns that will be returned for each row
 2 String[] mProjection =
 3 {
 4     UserDictionary.Words._ID,    // Contract class constant for the _ID column name
 5     UserDictionary.Words.WORD,   // Contract class constant for the word column name
 6     UserDictionary.Words.LOCALE  // Contract class constant for the locale column name
 7 };
 8 
 9 // Defines a string to contain the selection clause
10 String mSelectionClause = null;
11 
12 // Initializes an array to contain selection arguments
13 String[] mSelectionArgs = {""};

  The next snippet shows how to use ContentResolver.query(), using the User Dictionary Provider as an example. A provider client query is similar to an SQL query, and it contains a set of columns to return, a set of selection criteria, and a sort order. 
  The set of columns that the query should return is called a projection (the variable mProjection). 
  The expression that specifies the rows to retrieve is split into a selection clause and selection arguments. The selection clause is a combination of logical and Boolean expressions, column names, and values (the variable mSelectionClause). If you specify the replaceable parameter ? instead of a value, the query method retrieves the value from the selection arguments array (the variable mSelectionArgs).

  使用查询语句就可以访问provider内的数据。当select语句中有?时,用对应的参数数组代替。

  In the next snippet, if the user doesn't enter a word, the selection clause is set to null, and the query returns all the words in the provider. If the user enters a word, the selection clause is set to UserDictionary.Words.WORD + " = ?" and the first element of selection arguments array is set to the word the user enters. 

 1 /*
 2  * This defines a one-element String array to contain the selection argument.
 3  */
 4 String[] mSelectionArgs = {""};
 5 
 6 // Gets a word from the UI
 7 mSearchString = mSearchWord.getText().toString();
 8 
 9 // Remember to insert code here to check for invalid or malicious input.
10 
11 // If the word is the empty string, gets everything
12 if (TextUtils.isEmpty(mSearchString)) {
13     // Setting the selection clause to null will return all words
14     mSelectionClause = null;
15     mSelectionArgs[0] = "";
16 
17 } else {
18     // Constructs a selection clause that matches the word that the user entered.
19     mSelectionClause = UserDictionary.Words.WORD + " = ?";
20 
21     // Moves the user's input string to the selection arguments.
22     mSelectionArgs[0] = mSearchString;
23 
24 }
25 
26 // Does a query against the table and returns a Cursor object
27 mCursor = getContentResolver().query(
28     UserDictionary.Words.CONTENT_URI,  // The content URI of the words table
29     mProjection,                       // The columns to return for each row
30     mSelectionClause                   // Either null, or the word the user entered
31     mSelectionArgs,                    // Either empty, or the string the user entered
32     mSortOrder);                       // The sort order for the returned rows
33 
34 // Some providers return null if an error occurs, others throw an exception
35 if (null == mCursor) {
36     /*
37      * Insert code here to handle the error. Be sure not to use the cursor! You may want to
38      * call android.util.Log.e() to log this error.
39      *
40      */
41 // If the Cursor is empty, the provider found no matches
42 } else if (mCursor.getCount() < 1) {
43 
44     /*
45      * Insert code here to notify the user that the search was unsuccessful. This isn't necessarily
46      * an error. You may want to offer the user the option to insert a new row, or re-type the
47      * search term.
48      */
49 
50 } else {
51     // Insert code here to do something with the results
52 
53 }

  This query is analogous to the SQL statement: 

  SELECT _ID, word, locale FROM words WHERE word = <userinput> ORDER BY word ASC;

  In this SQL statement, the actual column names are used instead of contract class constants. 

  Protecting against malicious input
  If the data managed by the content provider is in an SQL database, including external untrusted data into raw SQL statements can lead to SQL injection.

  Consider this selection clause:

1 // Constructs a selection clause by concatenating the user's input to the column name
2 String mSelectionClause =  "var = " + mUserInput;

  If you do this, you're allowing the user to concatenate malicious SQL onto your SQL statement. For example, the user could enter "nothing; DROP TABLE *;" for mUserInput, which would result in the selection clause var = nothing; DROP TABLE *;. Since the selection clause is treated as an SQL statement, this might cause the provider to erase all of the tables in the underlying SQLite database (unless the provider is set up to catch SQL injection attempts). 

  To avoid this problem, use a selection clause that uses ? as a replaceable parameter and a separate array of selection arguments. When you do this, the user input is bound directly to the query rather than being interpreted as part of an SQL statement. Because it's not treated as SQL, the user input can't inject malicious SQL. Instead of using concatenation to include the user input, use this selection clause:

1 // Constructs a selection clause with a replaceable parameter
2 String mSelectionClause =  "var = ?";

  Set up the array of selection arguments like this: 

1 // Defines an array to contain the selection arguments
2 String[] selectionArgs = {""};

  Put a value in the selection arguments array like this: 

1 // Sets the selection argument to the user's input
2 selectionArgs[0] = mUserInput;

  A selection clause that uses ? as a replaceable parameter and an array of selection arguments array are preferred way to specify a selection, even if the provider isn't based on an SQL database. 

Displaying query results 第3步:处理返回的结果

  The ContentResolver.query() client method always returns a Cursor containing the columns specified by the query's projection for the rows that match the query's selection criteria. A Cursor object provides random read access to the rows and columns it contains. Using Cursor methods, you can iterate over the rows in the results, determine the data type of each column, get the data out of a column, and examine other properties of the results. Some Cursor implementations automatically update the object when the provider's data changes, or trigger methods in an observer object when the Cursor changes, or both. 

  查询返回的结果用Cursor指向。

  Note: A provider may restrict access to columns based on the nature of the object making the query. For example, the Contacts Provider restricts access for some columns to sync adapters, so it won't return them to an activity or service. 
  If no rows match the selection criteria, the provider returns a Cursor object for which Cursor.getCount() is 0 (an empty cursor). 
  If an internal error occurs, the results of the query depend on the particular provider. It may choose to return null, or it may throw an Exception. 
  Since a Cursor is a "list" of rows, a good way to display the contents of a Cursor is to link it to a ListView via a SimpleCursorAdapter.

  SimpleCursorAdapter系统写的与Cursor和ListView相关的适配器。


  The following snippet continues the code from the previous snippet. It creates a SimpleCursorAdapter object containing the Cursor retrieved by the query, and sets this object to be the adapter for a ListView:

 1 // Defines a list of columns to retrieve from the Cursor and load into an output row
 2 String[] mWordListColumns =
 3 {
 4     UserDictionary.Words.WORD,   // Contract class constant containing the word column name
 5     UserDictionary.Words.LOCALE  // Contract class constant containing the locale column name
 6 };
 7 
 8 // Defines a list of View IDs that will receive the Cursor columns for each row
 9 int[] mWordListItems = { R.id.dictWord, R.id.locale};
10 
11 // Creates a new SimpleCursorAdapter
12 mCursorAdapter = new SimpleCursorAdapter(
13     getApplicationContext(),               // The application's Context object
14     R.layout.wordlistrow,                  // A layout in XML for one row in the ListView
15     mCursor,                               // The result from the query
16     mWordListColumns,                      // A string array of column names in the cursor
17     mWordListItems,                        // An integer array of view IDs in the row layout
18     0);                                    // Flags (usually none are needed)
19 
20 // Sets the adapter for the ListView
21 mWordList.setAdapter(mCursorAdapter);

   Note: To back a ListView with a Cursor, the cursor must contain a column named _ID. Because of this, the query shown previously retrieves the _ID column for the "words" table, even though the ListView doesn't display it. This restriction also explains why most providers have a _ID column for each of their tables. 

  为了能在ListView中显示查询结果,在查询时必需指定_ID字段。


Getting data from query results 第4步:可以遍历查询结果,查具体字段内容。

  Rather than simply displaying query results, you can use them for other tasks. For example, you can retrieve spellings from the user dictionary and then look them up in other providers. To do this, you iterate over the rows in the Cursor: 

 1 // Determine the column index of the column named "word"
 2 int index = mCursor.getColumnIndex(UserDictionary.Words.WORD);
 3 
 4 /*
 5  * Only executes if the cursor is valid. The User Dictionary Provider returns null if
 6  * an internal error occurs. Other providers may throw an Exception instead of returning null.
 7  */
 8 
 9 if (mCursor != null) {
10     /*
11      * Moves to the next row in the cursor. Before the first movement in the cursor, the
12      * "row pointer" is -1, and if you try to retrieve data at that position you will get an
13      * exception.
14      */
15     while (mCursor.moveToNext()) {
16 
17         // Gets the value from the column.
18         newWord = mCursor.getString(index);
19 
20         // Insert code here to process the retrieved word.
21 
22         ...
23 
24         // end of while loop
25     }
26 } else {
27 
28     // Insert code here to report an error if the cursor is null or the provider threw an exception.
29 }

  Cursor implementations contain several "get" methods for retrieving different types of data from the object. For example, the previous snippet uses getString(). They also have a getType() method that returns a value indicating the data type of the column.

  Cursor提供了很多 查具体字段内容的函数。

 

转载于:https://www.cnblogs.com/sjjg/p/5928132.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值