Android Four components Learning ContentProvider II

Source: Internet
Author: User

The previous section learned what is ContentProvider, and the role of ContentProvider. And what is a URL. This section is a practice of learning from the previous section, i.e. defining your own ContentProvider

Well, practice is the only standard for testing truth. Then let's move on.

The first step: Create your own contentprovider, I named Mycontentprovider

public class Mycontentprovider extends ContentProvider {@Overridepublic int delete (Uri arg0, String arg1, string[] arg2) { TODO auto-generated method Stubreturn 0;} @Overridepublic String GetType (Uri arg0) {//TODO auto-generated method Stubreturn null;} @Overridepublic uri Insert (URI arg0, contentvalues arg1) {//TODO auto-generated method Stubreturn null;} @Overridepublic Boolean onCreate () {//TODO auto-generated method Stubreturn false;} @Overridepublic Cursor Query (Uri arg0, string[] arg1, String arg2, string[] arg3,string arg4) {//TODO auto-generated Meth OD stubreturn null;} @Overridepublic int update (Uri arg0, contentvalues arg1, String arg2, string[] arg3) {//TODO auto-generated method Stubre Turn 0;}}
These methods are familiar. This is not a common database additions and deletions to change it? The original ContentProvider provided us with the operation of the database. We just call the implementation.

Step two: Create a Sqliteopenhelper class that I named Mydbopenhelper

public class Mydbopenhelper extends Sqliteopenhelper {public String table_name= "user";p ublic mydbopenhelper (Context Context) {Super (context, "user.db", NULL, 1);//TODO auto-generated constructor stub} @Overridepublic void OnCreate (  Sqlitedatabase db) {//TODO auto-generated method Stubdb.execsql ("CREATE table User (_id integer primary key AutoIncrement, Name Char (ten), Age Integer (2), salary Integer (10)) "); @Overridepublic void Onupgrade (sqlitedatabase arg0, int arg1, int arg2) {//TODO auto-generated method stub}}
Create a table of table user in the creation method

Step three: Register ContentProvider in the configuration file

        <provider android:name= "Com.ui.contentprovider.MyContentProvider"                  android:authorities= " Com.ui.contentprovider "                   URL path                  android:exported=" true ">                                       expose yourself need to open        </provider>

Fourth step: Create an activity again to insert the data. Layout file is a four button


Now that everything is ready. We'll insert a set of data:

The OnCreate method of activity

public class Mainactivity extends Activity {contentresolver cresolver;        Get the URL Uri of the contentprovider you define Uri=uri.parse ("content://com.ui.contentprovider/");        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);       /* Get contentresolver*/Cresolver = Getcontentresolver (); }

Data that needs to be inserted when the Insert button is clicked

    public void Insert (View v)    {    log.i ("mainactivity", "---------Insert");    Contentvalues values = new Contentvalues ();        Values.put ("name", "Zhang San");    Values.put ("age", +);    Values.put ("Salary", 13000);    Cresolver.insert (URI, values);        Values.put ("name", "John Doe");    Values.put ("age", +);    Values.put ("Salary", 10000);    Cresolver.insert (URI, values);        Values.put ("name", "Harry");    Values.put ("age", +);    Values.put ("Salary", 200000);    Cresolver.insert (URI, values);        Values.put ("name", "Zhu Eight");    Values.put ("Age", ten);    Values.put ("salary");    Cresolver.insert (URI, values);    }

The Insert method provided to third parties in ContentProvider needs to be implemented:

public class Mycontentprovider extends ContentProvider {private Mydbopenhelper dhhelper;private sqlitedatabase db;@ Overridepublic Boolean onCreate () {log.i ("Mycontentprovider", "onCreate");// Call Mydbopenhelper's OnCreate method to create the database Dhhelper = new Mydbopenhelper (GetContext ());d B = dhhelper.getwritabledatabase (); return false;} Insert data for third-party apps @overridepublic uri insert (URI uri, contentvalues values) {log.i ("Mycontentprovider", "Insert");d B.insert (Dhhelper.table_name, null, values); return URI;}

The test is as follows: First run the activity of ContentProvider, and in running a third-party application, the results are:


Next, take a look at the delete operation, we delete the name of Harry classmate:

Activity when you click the Delete button:

    public void Delete (View v)    {    log.i ("mainactivity", "---------delete");    Cresolver.delete (URI, "name =?", New string[]{"Harry"});    

The delete in ContentProvider needs to be changed to:

@Overridepublic int Delete (Uri arg0, String whereclause, string[] whereargs) {log.i ("Mycontentprovider", "delete"); Db.delete (Dhhelper.table_name, Whereclause, Whereargs); return 0;}

The result of the operation is:


Next learn to modify the operation, because Zhu eight students recently performed better, the boss gave a raise. Plus 500.

Activity when you click the Update button to do the following:

    public void Update (View v)    {    log.i ("mainactivity", "---------Update");    Contentvalues values = new Contentvalues ();    Values.put ("Salary", 2500);    Cresolver.update (URI, values, "name =?", New string[]{"Zhu Eight"});    

ContentProvider is modified to:

@Overridepublic int update (Uri arg0, contentvalues values, String whereclause, string[] whereargs) {log.i (" Mycontentprovider "," Update "); int id = db.update (dhhelper.table_name, values, Whereclause, Whereargs); return ID;}

The effect is:

Next, the last operation, query operation, query wages greater than or equal to 10000:

Activity's Code:

    public void query (View v)    {    cursor cursor = cresolver.query (URI, NULL, "salary >=?", New string[]{"10000"}, Nu ll);    LOG.I ("Mainactivity", "---------query");    while (Cursor.movetonext ())    {    String name = cursor.getstring (Cursor.getcolumnindex ("name"));    int age = Cursor.getint (Cursor.getcolumnindex ("Age"));    int salary = Cursor.getint (Cursor.getcolumnindex ("salary"));    SYSTEM.OUT.PRINTLN (name + ";" + Age + ";" + salary);    }    }

The code in ContentProvider that needs to be modified:

@Overridepublic Cursor Query (Uri arg0, string[] projection, String selection, string[] selectionargs,string sortOrder) {L OG.I ("Mycontentprovider", "Query"); cursor cursor = db.query (dhhelper.table_name, projection, selection, Selectionargs, NULL, NULL, sortOrder); return cursor ;}

Serial-Port printing:


Well, about their own definition of their own contentprovider to here, we have achieved so the deletion and modification of the operation.






Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Four components Learning ContentProvider II

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.