。。。。

Source: Internet
Author: User

Source text: http://cw1057.blogspot.tw/2011/08/android-content-provider.html

The Android content provider can be viewed as a RESTful data wrapper, the main purpose of which is to share information between Android applications, which means that if the information doesn't need to be shared with other apps, it's not necessary to mention For content provider.
Android offers four kinds of data access:
Preferences-Saves the set value of the app in the form of Key/value. Files-app's specialized file. SQLite-is dedicated to the creation of the package of the data library. Network-access external data through the Internet. All four of these data access systems are dedicated to their own apps, and other apps are not shared, and if you share them with other apps, you can create content provider for that information.


REST (representational state Transfer) Simple

REST For example, to get all of the apples:

Content://idv.neil.appleprovider/apples

To obtain an apple:

Content://idv.neil.appleprovider/apples/16

There is also the URI of the add-fix.

Android content Providers

Android will store information such as Contacts or system settings in a SQLite repository, because only the app that builds the library can access the library through SQLite, which means that only the same package code can be used, and , so other apps can only be accessed through the content provider that it releases.

Through the SQLite

Open the Android plugin File Explorer, browse to/data/data/com.android.providers.contacts/databases, see contacts.db, select the file, press The "pull a file from the device" in the upper right of file Explorer allows you to capture the information file to the computer, and then download the free SQLite GUI, such as Sqliteman, to see the light.

Authority

The format of the content provider URI is content://authority/path1/path2/...,authority in Androidmanifest.xml, only Android can use the compressed Authority, such as contacts, have the full name of other apps.

<provider android:name= "Apple" android:authorities= "Idv.neil.AppleProvider"/>

MIME type

The data obtained through the content provider is a cursor object that is made up of row and column for a similar data library.

Android provides an HTTP-like way for content provider to know the type of a postback object by MIME type.

The MIME type is composed of two partial strings, such as text/html,text as the main type, HTML as the subtype, and the current main type is application, audio, image, multipart, text, video, subtype, or VND. The opening represents a specialized subtype, such as a vnd.me-excel, which, if it is X-open, is said to receive private agreement between the parties.

Anddroid follows the concept of MIME type, and applies it to a different situation because of the number of returned objects, and if you return a single Pen object, the MIME type format is Vnd.android.cursor.item/vnd.neil.apple, and if you return multiple objects, Vnd.android.cursor.dir/vnd.neil.apple.

Android uses the concept of MIME type to intent, that is, intent contains MIME type that decides to activate the activity of that intent, so the MIME type must be added domain name to do Uniq Ue.

Examples of Wordcloud

To develop ContentProvider steps:
Definition ContentProvider All information actually do ContentProvider registered ContentProvider Wordcloudprovider only one words table,words except _id only two, wor D and size, the goal is to do a blog like the common Tag cloud, the use of the higher the frequency of the tag font larger.

Enter Word and Size Press Add to add a words and restructure the page, and any words will bring out the original data for modification or removal.


Click Update or Delete to return to the original screen, and Empty will clear all the information in the table.

Define ContentProvider All information
The public class Wordcloudmetadata {   /** content provider's unique key is defined in manifest, and also in the externally-opened URI * * &nbs
p;   public static final String authority = "Idv.neil.provider.WordCloudProvider"; 
   /** uses DB to actually do content provider/    public static final String db_name = "wordcloud.db";    /** Be careful.

As soon as the version is changed, the old data will be emptied/    public static final int db_version = 1;

    Private Wordcloudmetadata () {   };    /** Words all information about the form, a content provider can have multiple tables/    public static final class Wo Rdstablemetadata implements Basecolumns {        private wordstablemetadata () { &

nbsp;     };
        public static final String table_name = "words";        /** words URI/        public static final URI C ONtent_uri = Uri.parse ("content://"                 +
Authority + "/words");        /** The MIME type of the number and the number of numbers/        public static final Stri
ng Content_dir_type = "vnd.android.cursor.dir/vnd.neil.words";         public static final String Content_item_type = "vnd.android.cursor.item/
Vnd.neil.words ";        /** Preset order/        public static final String Defau
Lt_sort_order = basecolumns._id                 + "ASC";        /** Define all the _id/       //Don't define the definition, because Basecolumns has been defined
The         public static final String Words_word = "WORD";
        public static final String words_size = "SIZE";    }
} 
actually do ContentProvider
public class Wordcloudprovider extends ContentProvider {private static final String TAG = "Wordcloudprovider"; Because there are times when DB is searching for the use of a join to name the conflict or because of the use of table alias to make the name of a complex//so define a relationship, the name used by the user is called the name of the application to DB, and the name of the user will be used.
	To define, or to say that user can only use the definition of this map in the name of the "private static map<string, string> Projectionmap;"
		static {Projectionmap = new hashmap<string, string> ();
		Projectionmap.put (wordstablemetadata._id, wordstablemetadata._id);
		Projectionmap.put (Wordstablemetadata.words_word, Wordstablemetadata.words_word);
	Projectionmap.put (Wordstablemetadata.words_size, wordstablemetadata.words_size); }//Because a contentprovider can handle many kinds of URIs, such as getting a bunch of information or just getting a piece of data//Android provides urimatcher to simplify the URI of the knowledge work private static final URI
	Matcher Urimatcher;
	private static final int words_dir_uri_indicator = 1;
	private static final int words_item_uri_indicator = 2;
		static {Urimatcher = new Urimatcher (urimatcher.no_match); When the URI conforms to the language of the first two parameters, return the third reference urimatcher.adDuri (wordcloudmetadata.authority, "words", words_dir_uri_indicator);
	Urimatcher.adduri (wordcloudmetadata.authority, "words/#", words_item_uri_indicator); }//DB Connector Tool private static class DBHelper extends Sqliteopenhelper {public DBHelper (context) {Super (CO
		ntext, wordcloudmetadata.db_name, NULL, wordcloudmetadata.db_version);
			@Override public void OnCreate (Sqlitedatabase db) {LOG.D (TAG, "Create db ..."); CREATE TABLE Language Db.execsql ("CREATE TABLE" + Wordstablemetadata.table_name +) ("+ wordstablemetadata._id +" int Eger primary KEY, "+ Wordstablemetadata.words_word +" text NOT NULL, "+ Wordstablemetadata.words_size +" inte
		Ger NOT NULL "+"); @Override public void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {log.d (TAG, "Modify db from
			Version "+ Oldversion +" to version "+ NewVersion +" ... "); When version changes, it usually drops the old table and then builds the table, so be careful that the old data is cleared DB.EXECSQL ("drop table if exists" + wordstablemetadata.table_name);
		This.oncreate (DB);

	} private DBHelper DBHelper;
		@Override public boolean onCreate () {LOG.D (TAG, "onCreate");
		New or rebuilt db This.dbhelper = new DBHelper (This.getcontext ());
	return true; @Override public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, String Sorto

		Rder) {Sqlitequerybuilder b = new Sqlitequerybuilder ();
		These two must be b.settables (wordstablemetadata.table_name);

		B.setprojectionmap (WORDCLOUDPROVIDER.PROJECTIONMAP);
		Different switch (Urimatcher.match (URI)) {case Words_dir_uri_indicator:break, which causes the syntax to be searched by different URIs;
			Case Words_item_uri_indicator:b.appendwhere (wordstablemetadata._id + "=" + uri.getpathsegments (). Get (1));
		Break
		Default:throw new IllegalArgumentException ("Unknown uri-" + uri);
		}//Data sort by String by = Wordstablemetadata.default_sort_order; if (! Textutils.isempty (SortOrder)) {by = by = SortordEr
		//Get cursor Sqlitedatabase db = This.dbHelper.getReadableDatabase ();

		Cursor C = b.query (db, Projection, selection, Selectionargs, NULL, NULL, by);
		Because it's getting data, you need to be notified of C.setnotificationuri (This.getcontext () getcontentresolver (), URI) when the data changes.
	return C; @Override public String getType (URI uri) {switch (Urimatcher.match (URI)) {case Words_dir_uri_indicator:retu
		RN Wordstablemetadata.content_dir_type;
		Case Words_item_uri_indicator:return Wordstablemetadata.content_item_type;
		Default:throw new IllegalArgumentException ("Unknown uri-" + uri); @Override public uri Insert (URI uri, contentvalues values) {//is only the URI of the Urimatcher.match (URI)!= Words_
		Dir_uri_indicator) {throw new IllegalArgumentException ("Unknown uri-" + uri);
		} contentvalues CV;
		if (values = = null) {CV = new contentvalues ();
		The reason for the else {//package layer is that the CV = new Contentvalues (values) may be modified. //Check the necessary!cv.containskey (WORDSTAblemetadata.words_word)) {throw new IllegalArgumentException ("The WORD is required!"); 
		} if (!cv.containskey (wordstablemetadata.words_size)) {throw new IllegalArgumentException ("The SIZE is required!");
		//Here you can also modify or recharge some data that can have a preset value sqlitedatabase db = This.dbHelper.getWritableDatabase ();
		Long rowId = Db.insert (wordstablemetadata.table_name, NULL, CV);
			if (RowId > 0) {log.d (TAG, "Insert" + rowId + "data");
			Uri Addeduri = Contenturis.withappendedid (Wordstablemetadata.content_uri, rowId);
			The data changed, and the Notification This.getcontext (). Getcontentresolver (). Notifychange (Addeduri, NULL);
		return Addeduri;
	} throw new IllegalArgumentException ("Failed to insert the data to URI-" + uri); @Override public int update (URI uri, contentvalues values, String selection, string[] selectionargs) {Sqlitedat
		Abase db = This.dbHelper.getWritableDatabase ();
		int cnt; Switch (Urimatcher.match (URI)) {case Words_dir_uri_indicator://Update multiple data CNT = dB.update (Wordstablemetadata.table_name, values, selection, Selectionargs);
		Break
			Case Words_item_uri_indicator://Update single data String rowId = Uri.getpathsegments (). get (1); CNT = db.update (Wordstablemetadata.table_name, values, wordstablemetadata._id + "=" + Rowi D + (Textutils.isempty (selection)?
			"": "and (" + Selection + ")), Selectionargs);
		Break
		Default:throw new IllegalArgumentException ("Unknown uri-" + uri);
		//information changed, Notification This.getcontext (). Getcontentresolver (). Notifychange (URI, NULL);
	return CNT; @Override public int Delete (URI Uri, String selection, string[] selectionargs) {sqlitedatabase db = This.dbhelper.
		Getwritabledatabase ();
		int cnt;
			Switch (Urimatcher.match (URI)) {case WORDS_DIR_URI_INDICATOR:LOG.D (TAG, ' Delete all data ... ');
					If the selection is empty, it empties the entire table, which is used as a function of emptying the table cnt = Db.delete (Wordstablemetadata.table_name, selection,
	Selectionargs);		Break
			Case Words_item_uri_indicator://Delete the single data String rowId = Uri.getpathsegments (). get (1);
			LOG.D (TAG, "Delete data [" + RowId + "] ..."); CNT = Db.delete (wordstablemetadata.table_name, wordstablemetadata._id + "=" + RowId + (T Extutils.isempty (selection)?
			"": "and (" + Selection + ")), Selectionargs);
		Break
		Default:throw new IllegalArgumentException ("Unknown uri-" + uri);
		//information changed, Notification This.getcontext (). Getcontentresolver (). Notifychange (URI, NULL);
	return CNT;
 }
}
Registered ContentProvider
<application android:icon= "@drawable/icon" android:label= "@string/app_name" >
<activity android:name= ". Wordcloudactivity ">
<intent-filter>
<action android:name=" Android.intent.action.MA In "/>
<category android:name=" Android.intent.category.LAUNCHER "/>
</intent-filte r>
</activity>
<provider android:name= ". Wordcloudprovider "
android:authorities=" Idv.neil.provider.WordCloudProvider "/>
</application>
How to use ContentProvider.
public class Wordcloudactivity extends activity {    private static final String TAG = "wordcloudactivity

";     @Override     public void onCreate (Bundle savedinstancestate) {    &
nbsp;   log.d (TAG, "onCreate");
        super.oncreate (savedinstancestate);
        Setcontentview (R.layout.wordcloud);
        this.loadwords ();    }     public void onclick (View v) {        log.d (TAG, "O
Nclick ... ");
        TextView iDTV = (TextView) This.findviewbyid (R.id.idvalue);
        EditText wordet = (edittext) This.findviewbyid (R.id.wordvalue);
        EditText sizeet = (edittext) This.findviewbyid (R.id.sizevalue);
        Words W;         switch (V.getid ()) {        case R.ID.ADDBTN:      
       log.d (TAG, "add word ...");
            w = new Words ();
            W.setword (Wordet.gettext (). toString ());             w.setsize (Integer.parseint (Sizeet.gettext (). toString ()))
;
            wordshelper.addwords (This.getcontentresolver (), W);
            this.resetform ();
            This.showbtns (true);
            break;         case R.ID.UPDATEBTN:            
LOG.D (TAG, "Update word ...");             w = new WordS ();
            W.setid (Integer.parseint (Idtv.gettext (). toString ()));
            W.setword (Wordet.gettext (). toString ());             w.setsize (Integer.parseint (Sizeet.gettext (). toString ()))
;
            wordshelper.updatewords (This.getcontentresolver (), W);
            this.resetform ();
            This.showbtns (true);
            break;         case R.ID.DELETEBTN:            
LOG.D (TAG, "delete word ...");             wordshelper.deletewords (This.getcontentresolver (),                    &nbsp
Integer.parseint (Idtv.gettext (). toString ()));
            this.resetform ();
            This.showbtns (true);
            break;         case R.ID.EMPTYBTN:            
LOG.D (TAG, "delete all words ...");
            wordshelper.deleteallwords (This.getcontentresolver ());
            break;        }        //Restructure page       & nbsp
This.loadwords ();    }     private void Loadwords () {        log.d (TAG, "loa
DWORDs ");
        list<words> wlist = Wordshelper.listwords (this);         LInearlayout TVs = (linearlayout) This.findviewbyid (R.id.tvs);
       //Empty TVs         tvs.removeallviews ();          for (Words w:wlist) {           // Add TextView to the page             Tvs.addview (This.createwordtextview (w), New Layoutparams (                   
Layoutparams.wrap_content, layoutparams.wrap_content));        }    }     private TextView Createwordtextview ( Words W) {        log.d (TAG, "Createwordtextview");       
  TextView TV = new TextView (this);
        Tv.settext (W.getword ());
        tv.settextsize (W.getsize ());         Tv.setid (W.getid ());
        tv.setclickable (true);         Tv.setonclicklistener (New OnC

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.