Content Providers-how to access a basic content provider

Source: Internet
Author: User
A content provider manages how to access data stored in the application repository. A content provider is a part of an application. It is often used to make the application interface work on the basis of the data it provides. However, content providers is mainly used for other applications to access and use it using a provider client object. In short, providers and providers
The client object provides a consistent and standard access interface for the data in the application, and it can also process cross-process communication and access to sensitive data accessing a provider. We can use ContentResolverClient object to access a content
Provider, we can use ContentResolverImplement content
The data source provided by the provider for crud
  ContentResolverThe object is running in the main thread of the application and may block the main thread. It can communicate across processes without too many operations, it serves as a communication between its own warehouse data and External table data.
When accessing a provider, you need to add content to the manifest File
Provider permissions permission Declaration we can use URI to locate a content provider and use SQL statements to describe the operations we want to perform data as table words

Word APP ID Frequency Locale _ Id
Mapreduce User1 100 En_us 1
Precompiler User14 200 Fr_fr 2
Applet User2 225 Fr_ca 3
Const User1 255 Pt_br 4
Int User5 100 En_uk 5

Query operationsWhen we perform a query, it is not like when we use a URL to locate a resource. A brain returns all the data, but a cursor object, this allows us to obtain data more intelligently.SQL: Select _ id, word, locale from words where WORD =?

Private void accesscontract (string msearchstring) {log. E (TAG, msearchstring); // URI uri = userdictionary. words. content_uri; // access a single row in a table // URI singleuri = contenturis. withappendedid (userdictionary. words. content_uri, 3); // a "projection" defines the columns that will be returned for each row // string [] mprojection = {userdictionary. 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}; // defines a string to contain the selection clause // query condition string mselectionclause = NULL; // initializes an array to contain selection arguments // query condition value string [] mselectionargs = {""}; // remembe R to insert code here to check for invalid or malicious input. // if the word is the empty string, gets everything if (textutils. isempty (msearchstring) {// setting the selection clause to null will return all words mselectionclause = NULL; mselectionargs [0] = "";} else {// constructs a selection clause that matches the word that the user entered. mselectionclause = userdictionary. words. word + "=? "; // Moves the user's input string to the selection arguments. mselectionargs [0] = msearchstring;} // queries the user dictionary and returns results cursor mcursor = getcontentresolver (). query (Uri, // The content URI of the words table mprojection, // The columns to return for each row mselectionclause, // selection criteria // null, mselectionargs, // selection criteria // null, userdictionary. Words. word); // The sort order for the returned rows // last generate SQL // select _ id, word, frequency, locale from words where WORD = <userinput> order by word ASC; // some providers return NULL if an error occurs, others throw an exception if (null = mcursor) {/** insert code here to handle the error. be sure not to use the cursor! You may want to * Call android. util. log. E () to log this error. ** // If the cursor is empty, the provider found no matches log. E (TAG, "mcursor is null");} else if (mcursor. getcount () <1) {/** insert code here to your y the user that the search was unsuccessful. this isn't necessarily * an error. you may want to offer the user the option to Insert a new row, or re-type the * search term. */log. E (TAG, "mcursor is empty");} else {// insert code here to do something with the results log. E (TAG, "mcursor is not empty"); // display (mcursor);} // mcursor. close ();}

Insert operation
Encapsulate the fields and values to be inserted with contentvaluesSQL: insert into words (_ id, locale, word, frequency) values (?,?,?,?)

       private void insert(){              // Defines a new Uri object that receives the result of the insertion             Uri mNewUri;              //...              // Defines an object to contain the new values to insert             ContentValues mNewValues = new ContentValues();              /*              * Sets the values of each column and inserts the word. The arguments to the "put"              * method are "column name" and "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.Words. CONTENT_URI,   // the user dictionary content URI                 mNewValues                          // the values to insert             );                          Log. e(TAG, mNewUri.getPath());       }

Update operation SQL: Update words set locale =? Where locale =?
          private void update(){              // Defines an object to contain the updated values             ContentValues mUpdateValues = new ContentValues();              // Defines selection criteria for the rows you want to update             String mSelectionClause = UserDictionary.Words.LOCALE +  " LIKE ?";             String[] mSelectionArgs = { "en_%"};              // Defines a variable to contain the number of updated rows              int mRowsUpdated = 0;              //...              /*              * Sets the updated value and updates the selected words.              */             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 to             );                    Log. e(TAG, "effect row "+mRowsUpdated);                    }

Delete operation
SQL: delete from words where WORD =?
        private void delete(){              // Defines selection criteria for the rows you want to delete             String mSelectionClause = UserDictionary.Words. WORD + " = ?" ;             String[] mSelectionArgs = { "insert"};              // Defines a variable to contain the number of rows deleted              int mRowsDeleted = 0;              //...              // Deletes the words that match the selection criteria             mRowsDeleted = getContentResolver().delete(                 UserDictionary.Words. CONTENT_URI,   // the user dictionary content URI                 mSelectionClause,                    // the column to select on                 mSelectionArgs                      // the value to compare to             );                          Log. e(TAG, "delete effect row "+mRowsDeleted);       }

Use simplecursoradapter to conveniently display data of a data source
             private void display(Cursor mCursor) {              // Defines a list of columns to retrieve from the Cursor and load into an output row             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 a list of View IDs that will receive the Cursor columns for each row              int[] mWordListItems = { R.id.dictWord, R.id.locale};              // Creates a new SimpleCursorAdapter             SimpleCursorAdapter mCursorAdapter = new SimpleCursorAdapter(                 getApplicationContext(),               // The application's Context object                 R.layout. wordlist_item,                  // 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                 );                                    // Flags (usually none are needed)              // Sets the adapter for the ListView              mWordList.setAdapter(mCursorAdapter);       }

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.