Content provider for Android data sharing)

Source: Internet
Author: User

5. Access Content Provider

First, we will learn how to use content provider (including the content provided by the system, such as creating an SMS receiving and receiving system ).

Users of content providers cannot directly access the content provider instance. They can only use contentresolver to proxy in the middle. The client directly uses the content resolver object for interaction. The content Resolvers method provides the basic continuous data storage functions CRUD (create, retrieve, update, and delete ). The client can obtain the contentresolver instance through the following activity member method. However, when you access the provider, your application should request the corresponding permissions in the mainfest file.

ContentResolver cr= getContext().getContentResolver();

Contentresolver provides five basic content provider operations. When you create your own content provider, that is, inherit the contentprovider class, it means that you also implement these five methods at the same time (which will be introduced in subsequent chapters ).

1、final Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder)//Query the given URI, returning a Cursor over the result set.final Cursor managedQuery(Uri uri,String[] projection,String selection,String[]selectionArgs,String sortOrder)2、final Uri insert(Uri url, ContentValues values)//Inserts a row into a table at the given URL.3、final int  update(Uri uri, ContentValues values, String where, String[] selectionArgs)//Update row(s) in a content URI.4、final int  delete(Uri url, String where, String[] selectionArgs)//Deletes row(s) specified by a content URI.5、final String getType(Uri url)//Return the MIME type of the given content URL.

The preceding two query methods differ in that the life cycle of the cursor of the managedquery () method is managed by the activity. Benefits of Management: The activity helps you deal with details, such as unmounting when the activity is paused and re-requesting when the activity starts again. For cursor not managed by activity, you can use this function to manage activit:

Activity.startManagingCursor(Cursor cursor)

6. query data from the provider

The following two steps are involved: User dictinary)

(1) Request read permission. Configure Android. Permission. read_user_dictionary in the mainfest File

(2) custom query code. There are two main processing methods: one is to display the query results and the other is to obtain the query data.

In addition, when you precisely search for a record, it means that your URI needs to contain its _ id value. You can append the record using the following two methods:

Uri myPerson = ContentUris.withAppendedId(People.CONTENT_URI, 23);Uri myPerson = Uri.withAppendedPath(People.CONTENT_URI, "23");

6.1 first, you need to construct a query

// Specify the field string [] mprojection = {userdictionary for each row to be returned. words. _ id, // Contract class constant for the _ ID column name userdictionary. words. word, // Contract class constant for the word column name userdictionary. words. locale // Contract class constant for the locale column name}; // define the query clause string (similar to the SQL WHERE clause, but without the where keyword) string mselectionclause = NULL; // initialize the array, which contains the parameter values of the query clause (that is, the Placeholder "?" Value) string [] mselectionargs = {""};/** this defines a one-element string array to contain the selection argument. */string [] mselectionargs = {""}; // obtain the user input msearchstring = msearchword. gettext (). tostring (); // check whether the user input is valid. // if it is null, null is used to query all data if (textutils. isempty (msearchstring) {mselectionclause = NULL; mselectionargs [0] = "" ;}else {// construct a query clause mselectionclause = userdictionary based on user input. words. word + "=? "; // Mselectionargs [0] = msearchstring;} // query by the contextresolver object, return the cursor object mcursor = getcontentresolver (). query (userdictionary. words. content_uri, // The content URI of the words table mprojection, // The columns to return for each row mselectionclause // either null, or the word the user entered mselectionargs, // either empty, or the string the user entered msortorder); // The sort order for the returned rows // process the query cursor (null or exception) if (null = mcursor) {/** handle the error. At this time, mcursor cannot use * Call android. util. log. E () to log this error. ** // If the cursor is empty, the provider found no matches} else if (mcursor. getcount () <1) {/** query failed, notifying users of invalid query clauses * may also be the input you want to recommend to users */} else {// process correct query results}

Note: Use the Placeholder "?", It can effectively block malicious SQL statements, that is, why mselectionclause and mselectionargs are used indirectly to construct where statements.

 

6.2.1 display query results

The query returns cursor, which is a list row object type. Therefore, it is best to use the simplecursoradapter filler to link the cursor content to the listview.

(1) If selection is not matched, provider returns an empty cursor object. At this time, cursor. getcount () is 0

(2) If an internal error occurs, the query result depends on the provider (null or exception may be returned)

// Define string [] mwordlistcolumns = {userdictionary. words. word, // Contract class constant containing the word column name userdictionary. words. locale // Contract class constant containing the locale column name}; // defines the ID of the view to be filled in the returned field, that is, int to [] int [] mwordlistitems = {R. id. dictword, R. id. locale}; // creates a new simplecursoradaptermcursoradapter = new simplecursoradapter (getapplicationcontext (), // The application's context object R. layout. wordlistrow, // a layout in XML for one row in the listview mcursor, // The result from the query mwordlistcolumns, // a string array of column names in the cursor mwordlistitems, // an integer array of view IDs in the row layout 0); // flags (usually none are needed) // sets the adapter for the listviewmwordlist. setadapter (mcursoradapter );

6.2.2 obtain data from query results

// Obtain the index int Index = mcursor for this field. getcolumnindex (userdictionary. words. word);/** if the cursor is valid, null, internal error, or exception */If (mcursor! = NULL) {/** before executing the while statement, that is, moving, you should first move the cursor to the next line. * if you try to directly query data, an exception will be obtained, because "Row Pointer" is-1 */while (mcursor. movetonext () {// obtain the corresponding value from the field index newword = mcursor. getstring (INDEX); // process the queried value .... // end of while loop} else {// If cursor is null or the provider throws an exception, process}

6.3 insert data:

Use the contentresolver. insert () method to Insert a new row to the provider, and return the URI of the newly added row.

// Define a new URI object that receives the inserted result URI mnewuri ;... // define an object to save the value to be inserted contentvalues mnewvalues = new contentvalues ();/** set the value of each inserted field, parameter: field name, field value */mnewvalues. put (userdictionary. words. app_id, "example. user "); mnewvalues. put (userdictionary. words. locale, "en_us"); mnewvalues. put (userdictionary. words. word, "insert"); mnewvalues. put (userdictionary. words. frequency, "100"); mnewuri = getcontentresolver (). insert (userdictionary. word. content_uri, // The user dictionary content URI mnewvalues // The values to insert );

Note: (1) because of the SQLite database features, you do not need to place data of the same type as the field, or even use contentvalues. putnull () without specifying a value ().

(2) autoincrement. The provider assigns a unique _ id to each row as the primary key.

(3) The returned new URI is as follows. <id_value> is the _ id value. You can use this ID to perform corresponding operations on this row. Obtain the _ id value through contenturis. parseid ();

content://user_dictionary/words/<id_value>

6.4 update data

The client uses contentresolver. Update () to update data and returns the number of updated rows. Use the contentvalues object to store temporary data. You only need to store the fields you want to change. If you want to clear it, set the value to null.

// Define the contentvalues object and save the data contentvalues mupdatevalues = new contentvalues (); // define the query clause string mselectionclause = userdictionary for the row to be updated. words. locale + "like? "; String [] mselectionargs = {" en _ % "}; // defines a variable, storing the total number of updated rows int mrowsupdated = 0 ;... /** worth storing objects to be updated */mupdatevalues. putnull (userdictionary. words. locale); mrowsupdated = getcontentresolver (). update (userdictionary. words. content_uri, // The user dictionary content URI mupdatevalues // The columns to update mselectionclause // The column to select on mselectionargs/the value to compare );

6.5 delete data

Similar to a query, specifying the conditions for deleting rows will return the number of rows to be deleted. When performing the delete operation, a certain number of errors should be taken for user input to prevent malicious input.

// Define the deletion condition string mselectionclause = userdictionary. Words. app_id + "like? "; String [] mselectionargs = {" user "}; // defines the variable, storing the number of deleted rows int mrowsdeleted = 0 ;... // Delete mrowsdeleted = getcontentresolver (). delete (userdictionary. words. content_uri, // The user dictionary content URI mselectionclause // The column to select on mselectionargs // The value to compare );
 

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.