Contentprovider of four Android Components

Source: Internet
Author: User

Contentprovider mainly provides a unified interface for accessing data. Once a class inherits contengprovider, we will call this application contengprovider)

Steps for using contentprovider:

1. Write a class to inherit contentprovider and rewrite some of the methods.

2. Declare your defined provider in the androidmanifest. xml file

 

Before using contentprovider, you must understand the usage of two classes:

Urimatcher:

The urimatcher class is used to match a URI. Its usage is as follows: the first step is to register all the URI paths you need to match, as shown below: // constant urimatcher. no_match indicates that the return code does not match any path.
Urimatcher smatcher = new urimatcher (urimatcher. no_match); // If the match () method matches the content: // CN. itcast. provider. personprovider/person path, 1 is returned.
Smatcher. adduri ("cn. itcast. provider. personprovider ",
"Person", 1); // Add the URI to be matched. If yes, the matching code is returned.
// If the match () method matches the content: // CN. itcast. provider. personprovider/person/230 path, the return matching code is 2.
Smatcher. adduri ("CN. itcast. provider. personprovider", "person/#", 2); // # It is a wildcard
Contenturis: The contenturis class is used to obtain the ID part after the URI path. It has two practical methods: Withappendedid (Uri, ID)Used to add the ID part to the path: URI uri = URI. parse ("content: // CN. itcast. provider. personprovider/person ")
Uri resulturi = contenturis. withappendedid (Uri, 10 );
// The generated URI is: Content: // CN. itcast. provider. personprovider/person/10. Parseid (URI)The method is used to obtain the ID part from the path: URI uri = URI. parse ("content: // CN. itcast. provider. personprovider/person/10 ")
Long personid = contenturis. parseid (URI); // The returned result is: 10. Use contentprovider: 1. Define a class to inherit from sqliteopenhelper
Public class mydbhelper extends sqliteopenhelper {public static final int version = 1; public static final string db_name = "gjun"; Public mydbhelper (context) {super (context, db_name, null, version); // todo auto-generated constructor stub} @ overridepublic void oncreate (sqlitedatabase dB) {// todo auto-generated method stub // normally create the table db.exe csql ("create table student (ID integer primary key autoincrement, name varchar (20)") in the data library here ))");} @ overridepublic void onupgrade (sqlitedatabase dB, int oldversion, int newversion) {// todo auto-generated method stub }}

2. Define a class that inherits the contentprovider

public class MyProvider extends ContentProvider{private MyDBHelper helper;private SQLiteDatabase db;private static final String AUTHORI="com.provider.db.myprovider";private static final int ITEM=1;private static final int ITEMS=2;private static final String CONTENT_URI="content://com.provider.db.myprovider";private static final UriMatcher matcher;static{matcher=new UriMatcher(UriMatcher.NO_MATCH);matcher.addURI(AUTHORI,"student",ITEMS);matcher.addURI(AUTHORI,"student/#",ITEM);}@Overridepublic int delete(Uri uri, String selection, String[] selectionArgs){// TODO Auto-generated method stubswitch(matcher.match(uri)){case ITEM:int num=0;StringBuilder sb=new StringBuilder();long id=ContentUris.parseId(uri);sb.append("id="+id);db=helper.getWritableDatabase();if(selection!=null && !selection.equals("")){sb.append(" and selection");}num=db.delete("student",sb.toString(),selectionArgs);return num;case ITEMS:db=helper.getWritableDatabase();num=db.delete("student", selection,selectionArgs);return num;default:throw new IllegalArgumentException("UnKnow Uri:"+uri.toString());}}@Overridepublic String getType(Uri uri){// TODO Auto-generated method stubswitch(matcher.match(uri)){case ITEM:return "vnd.android.cursor.item/student";case ITEMS:return "vnd.android.cursor.dir/student";default:throw new IllegalArgumentException("UnKnow URI:"+uri.toString());}}@Overridepublic Uri insert(Uri uri, ContentValues values){// TODO Auto-generated method stublong id=0;Uri result=null;switch(matcher.match(uri)){case ITEM:db=helper.getWritableDatabase();id=db.insert("student", null, values);result=Uri.parse(uri.toString().substring(0, uri.toString().lastIndexOf("/")+1));ContentUris.withAppendedId(result, id);return result;case ITEMS:db=helper.getWritableDatabase();id=db.insert("student", null, values);result=ContentUris.withAppendedId(uri, id);return result;default:throw new IllegalArgumentException("UnKnow URI:"+uri.toString());}}@Overridepublic boolean onCreate(){// TODO Auto-generated method stubhelper=new MyDBHelper(this.getContext());return true;}@Overridepublic Cursor query(Uri uri, String[] projection, String selection,String[] selectionArgs, String sortOrder){// TODO Auto-generated method stubdb=helper.getReadableDatabase();Cursor cursor=null;switch(matcher.match(uri)){case ITEM:StringBuilder sb=new StringBuilder();long id=ContentUris.parseId(uri);sb.append("id="+id);if(selection!=null && selection.equals("")){sb.append("and selection");}cursor=db.query("student", projection, sb.toString(), selectionArgs,null, null,sortOrder);return cursor;case ITEMS:return db.query("student", projection, selection, selectionArgs, null, null, sortOrder);default:throw new IllegalArgumentException("UnKnow URI:"+uri.toString());}}@Overridepublic int update(Uri uri, ContentValues values, String selection,String[] selectionArgs){// TODO Auto-generated method stubdb=helper.getWritableDatabase();int num=0;switch(matcher.match(uri)){case ITEM:StringBuilder sb=new StringBuilder();long id=ContentUris.parseId(uri);sb.append("id="+id);if(selection!=null && selection.equals("")){sb.append("and selection");}num=db.update("student", values, sb.toString(), selectionArgs);return num;case ITEMS:num=db.update("student", values, selection, selectionArgs);return num;default:throw new IllegalArgumentException("UnKnow URI:"+uri.toString());}}}

3. Compile a test class

Public class mainactivity extends activity implements onclicklistener {/** called when the activity is first created. */private button btnadd = NULL; private button btnadds = NULL; private button btndel = NULL; private button btndels = NULL; private button btnupdate = NULL; private button btnupdates = NULL; private button btnfind = NULL; private button btnfinds = NULL; private contentresolver resolver = NULL; private URI = Uri. parse ("content: // COM. provider. DB. myprovider/student "); @ override public void oncreate (bundle savedinstancestate) {super. oncreate (savedinstancestate); setcontentview (R. layout. main); Init (); initlistener (); resolver = This. getcontentresolver ();} public void Init () {btnadd = (button) This. findviewbyid (R. id. btnadd); btnadds = (button) This. findviewbyid (R. id. btnadds); btndel = (button) This. findviewbyid (R. Id. btndel); btndels = (button) This. findviewbyid (R. id. btndels); btnupdate = (button) This. findviewbyid (R. id. btnupdate); btnupdates = (button) This. findviewbyid (R. id. btnupdates); btnfind = (button) This. findviewbyid (R. id. btnfind); btnfinds = (button) This. findviewbyid (R. id. btnfinds);} public void initlistener () {btnadd. setonclicklistener (this); btnadds. setonclicklistener (this); btndel. setonclicklistener (this ); Btndels. setonclicklistener (this); btnupdate. setonclicklistener (this); btnupdates. setonclicklistener (this); btnfind. setonclicklistener (this); btnfinds. setonclicklistener (this) ;}@ overridepublic void onclick (view v) {// todo auto-generated method stuburi nowuri = NULL; If (v. GETID () = R. id. btnadd) {nowuri = contenturis. withappendedid (Uri, 1); contentvalues CV = new contentvalues (); cv. put ("name", "Gavin"); resol Ver. insert (nowuri, CV); toast. maketext (this, "added with success! ", Toast. length_short ). show ();} else if (v. GETID () = R. id. btnadds) {contentvalues CV = new contentvalues (); cv. put ("name", "Tom"); resolver. insert (Uri, CV); toast. maketext (this, "added successfully with marker! ", Toast. length_short ). show ();} else if (v. GETID () = R. id. btndel) {nowuri = contenturis. withappendedid (Uri, 1); resolver. delete (nowuri, null, null); toast. maketext (this, "you have successfully deleted a single user !! ", Toast. length_short ). show ();} else if (v. GETID () = R. id. btndels) {resolver. delete (Uri, null, null); toast. maketext (this, "except all tokens used successfully !! ", Toast. length_short ). show ();} else if (v. GETID () = R. id. btnfind) {nowuri = contenturis. withappendedid (Uri, 6); cursor = resolver. query (nowuri, null, null); cursor. movetofirst (); int id = cursor. getint (cursor. getcolumnindex ("ID"); string name = cursor. getstring (cursor. getcolumnindex ("name"); toast. maketext (this, "ID" + ID + "name" + name, toast. length_short ). show ();} else if (v. GETID () = R. id. btnfinds) {cursor = resolver. query (Uri, null, null); cursor. move (2); int id = cursor. getint (cursor. getcolumnindex ("ID"); string name = cursor. getstring (cursor. getcolumnindex ("name"); toast. maketext (this, "ID" + ID + "name" + name, toast. length_short ). show ();} else if (v. GETID () = R. id. btnupdate) {nowuri = contenturis. withappendedid (Uri, 6); contentvalues CV = new contentvalues (); cv. put ("name", "Jack"); resolver. update (nowuri, CV, null, null);} else if (v. GETID () = R. id. btnupdates) {contentvalues CV = new contentvalues (); cv. put ("name", "Jack"); resolver. update (Uri, CV, null, null );}}}

 

 

 

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.