Android Custom ContentProvider Instance _android

Source: Internet
Author: User
The following is Testbaidu
Mainactivity is as follows:
Copy Code code as follows:

Package Cn.testbaidu;
Import Android.net.Uri;
Import Android.os.Bundle;
Import Android.view.View;
Import Android.view.View.OnClickListener;
Import Android.widget.Button;
Import android.app.Activity;
Import Android.content.ContentResolver;
Import android.content.ContentValues;
Import Android.database.Cursor;
/**
* Demo Description:
* Apply a (Testbaidu) invoke another application (Testcontentprovider)
* Custom ContentProvider, that is:
* 1 Use of custom ContentProvider
* 2 Other applications call the ContentProvider
*
* Test Method:
* 1 to test ContentProvider in turn (note this order)
* 2 Other applications query the ContentProvider data
*
*/
public class Mainactivity extends activity {
Private Button Maddbutton;
Private Button Mdeletebutton;
Private Button Mupdatebutton;
Private Button Mquerybutton;
Private Button Mtypebutton;
Private Contentresolver Mcontentresolver;
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
Init ();
}
private void init () {
Mcontentresolver=this.getcontentresolver ();

maddbutton= (Button) Findviewbyid (R.id.addbutton);
Maddbutton.setonclicklistener (New Clicklistenerimpl ());

mdeletebutton= (Button) Findviewbyid (R.id.deletebutton);
Mdeletebutton.setonclicklistener (New Clicklistenerimpl ());

mupdatebutton= (Button) Findviewbyid (R.id.updatebutton);
Mupdatebutton.setonclicklistener (New Clicklistenerimpl ());

mquerybutton= (Button) Findviewbyid (R.id.querybutton);
Mquerybutton.setonclicklistener (New Clicklistenerimpl ());

mtypebutton= (Button) Findviewbyid (R.id.typebutton);
Mtypebutton.setonclicklistener (New Clicklistenerimpl ());

}
Private class Clicklistenerimpl implements onclicklistener{
@Override
public void OnClick (View v) {
Switch (V.getid ()) {
Case R.id.addbutton:
Person Person=null;
for (int i = 0; i < 5; i++) {
Person=new person ("xiaoming" +i, "9527" +i, (8888+i));
Testinsert (person);
}
Break
Case R.id.deletebutton:
Testdelete (1);
Break
Case R.id.updatebutton:
Testupdate (3);
Break
Case R.id.querybutton:
Query table
Queryfromcontentprovider (-1);

Querying for personid=2 data
Testquery (2);
Break
Case R.id.typebutton:
Testtype ();
Break
Default
Break
}

}

}
private void Testinsert (person person) {
Contentvalues contentvalues=new contentvalues ();
Contentvalues.put ("Name", Person.getname ());
Contentvalues.put ("Phone", Person.getphone ());
Contentvalues.put ("Salary", person.getsalary ());
Uri inserturi=uri.parse ("Content://cn.bs.testcontentprovider/person");
Uri Returnuri=mcontentresolver.insert (Inserturi, contentvalues);
SYSTEM.OUT.PRINTLN ("Add Data: returnuri=" +returnuri);
}

private void Testdelete (int index) {
Uri uri=uri.parse ("content://cn.bs.testcontentprovider/person/" +string.valueof (index));
Mcontentresolver.delete (URI, NULL, NULL);
}

private void testupdate (int index) {
Uri uri=uri.parse ("content://cn.bs.testcontentprovider/person/" +string.valueof (index));
Contentvalues values=new contentvalues ();
Values.put ("name", "Hanmeimei");
Values.put ("Phone", "1234");
Values.put ("Salary", 333);
Mcontentresolver.update (URI, values, NULL, NULL);
}
private void Testquery (int index) {
Uri Uri=null;
if (index<=0) {
Query table
Uri=uri.parse ("Content://cn.bs.testcontentprovider/person");
} else {
Query for a piece of data by ID
Uri=uri.parse ("content://cn.bs.testcontentprovider/person/" +string.valueof (index));
}

Corresponding to the above: query table
Cursor cursor= mcontentresolver.query (URI, NULL, NULL, NULL, NULL);

Corresponding to the above: query personid=2 data
Note: Because name is a varchar field, you should write "Name= ' Xiaoming1"
If you write a "name=xiaoming1" query, you will get an error
Cursor cursor= mcontentresolver.query (URI, NULL, "Name= ' xiaoming1 '", NULL, NULL);

while (Cursor.movetonext ()) {
int Personid=cursor.getint (Cursor.getcolumnindex ("PersonID"));
String name=cursor.getstring (Cursor.getcolumnindex ("name"));
String phone=cursor.getstring (Cursor.getcolumnindex ("Phone"));
int Salary=cursor.getint (Cursor.getcolumnindex ("salary"));
SYSTEM.OUT.PRINTLN ("Query obtained: personid=" + personid+ ", name=" +name+ ", phone=" +phone+ ", salary=" +salary ");
}
Cursor.close ();
}

private void Testtype () {
Uri diruri=uri.parse ("Content://cn.bs.testcontentprovider/person");
String Dirtype=mcontentresolver.gettype (Diruri);
System.out.println ("Dirtype:" +dirtype);

Uri itemuri=uri.parse ("CONTENT://CN.BS.TESTCONTENTPROVIDER/PERSON/3");
String Itemtype=mcontentresolver.gettype (Itemuri);
System.out.println ("ItemType:" +itemtype);
}
}

The person is as follows:
Copy Code code as follows:

Package Cn.testbaidu;
public class Person {
Private Integer ID;
private String name;
Private String phone;
Private Integer salary;
Public person (string name, string Phone,integer salary) {
THIS.name = name;
This.phone = phone;
This.salary=salary;
}
Public person (Integer ID, string name, String Phone,integer salary) {
This.id = ID;
THIS.name = name;
This.phone = phone;
This.salary=salary;
}
Public Integer getId () {
return ID;
}
public void SetId (Integer id) {
This.id = ID;
}
Public String GetName () {
return name;
}
public void SetName (String name) {
THIS.name = name;
}
Public String Getphone () {
return phone;
}
public void Setphone (String phone) {
This.phone = phone;
}
Public Integer getsalary () {
return salary;
}
public void Setsalary (Integer salary) {
This.salary = salary;
}
@Override
Public String toString () {
return "person [id=" + ID + ", name=" + name + ", phone=" + phone+ ", salary=" + salary + "]";
}



}

Main.xml is as follows:
Copy Code code as follows:

<relativelayout xmlns:android= "Http://schemas.android.com/apk/res/android"
Xmlns:tools= "Http://schemas.android.com/tools"
Android:layout_width= "Match_parent"
android:layout_height= "Match_parent" >
<button
Android:id= "@+id/addbutton"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:layout_centerhorizontal= "true"
android:layout_margintop= "30dip"
android:text= "Increase"
Android:textsize= "20sp"/>
<button
Android:id= "@+id/deletebutton"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:layout_centerhorizontal= "true"
android:layout_margintop= "30dip"
android:layout_below= "@id/addbutton"
android:text= "Delete"
Android:textsize= "20sp"/>
<button
Android:id= "@+id/updatebutton"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:layout_centerhorizontal= "true"
android:layout_margintop= "30dip"
android:layout_below= "@id/deletebutton"
android:text= "Modify"
Android:textsize= "20sp"/>
<button
Android:id= "@+id/querybutton"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:layout_centerhorizontal= "true"
android:layout_margintop= "30dip"
android:layout_below= "@id/updatebutton"
android:text= "Query"
Android:textsize= "20sp"/>
<button
Android:id= "@+id/typebutton"
Android:layout_width= "Wrap_content"
android:layout_height= "Wrap_content"
Android:layout_centerhorizontal= "true"
android:layout_margintop= "30dip"
android:layout_below= "@id/querybutton"
android:text= "Type"
Android:textsize= "20sp"/>
</RelativeLayout>

The following is Testcontentprovider
Mainactivity is as follows:
Copy Code code as follows:

Package cn.testcontentprovider;
Import android.app.Activity;
Import Android.os.Bundle;
public class Mainactivity extends activity {
@Override
protected void OnCreate (Bundle savedinstancestate) {
Super.oncreate (savedinstancestate);
Setcontentview (R.layout.main);
}
}

Contentprovidertest is as follows:
Copy Code code as follows:

Package cn.testcontentprovider;
Import Android.content.ContentProvider;
Import Android.content.ContentUris;
Import android.content.ContentValues;
Import Android.content.UriMatcher;
Import Android.database.Cursor;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.net.Uri;
/**
* Precautions:
* Properties when registering ContentProvider in Androidmanifest.xml
* android:exported= "True" indicates that other application access is allowed.
* So testbaidu this application can access the ContentProvider of the place
*/
public class Contentprovidertest extends ContentProvider {
Private Dbopenhelper Dbopenhelper;
Private Urimatcher Uri_matcher;
private static final int PERSONS = 0;
private static final int person = 1;

@Override
public Boolean onCreate () {
Initurimatcher ();
Dbopenhelper=new Dbopenhelper (GetContext ());
return true;
}
Initialize Urimatcher
private void Initurimatcher () {
Uri_matcher=new Urimatcher (Urimatcher.no_match);
Represents the return of all the person, where persons is the identity code for that particular URI
Uri_matcher.adduri ("Cn.bs.testcontentprovider", "person", PERSONS);
Represents the return of a person who is the identity code for that particular URI
Uri_matcher.adduri ("Cn.bs.testcontentprovider", "person/#", person);
}
/**
* Insert operation:
* Insert operation only one possibility: INSERT into a table
* Returns the URI corresponding to the new record
* Method Db.insert () returns the primary key value of the result for the new record
*/
@Override
Public URI insert (URI uri, contentvalues values) {
Sqlitedatabase db=dbopenhelper.getwritabledatabase ();
Switch (Uri_matcher.match (URI)) {
Case PERSONS:
Long Rowid=db.insert ("person", "name,phone,salary", values);
Return Contenturis.withappendedid (URI, ROWID);
Default
throw new IllegalArgumentException ("Unknown URI" +uri.tostring ());
}
}

/**
* Update operation:
* There are two possibilities for update operations: updating a table or updating a piece of data
* The principle of updating a piece of data is similar to querying a certain data, see below.
*/
@Override
public int update (URI uri, contentvalues values, String selection, string[] Selectionargs) {
Sqlitedatabase db=dbopenhelper.getwritabledatabase ();
int updatanum=0;
Switch (Uri_matcher.match (URI)) {
Update table
Case PERSONS:
Updatanum=db.update ("person", values, selection, Selectionargs);
Break
Update a piece of data by ID
Case Person:
Long Id=contenturis.parseid (URI);
String where= "personid=" +ID;
if (selection!=null&&! "". Equals (Selection.trim ())) {
where=selection+ "and" +where;
}
Updatanum=db.update ("person", values, where, Selectionargs);
Break
Default
throw new IllegalArgumentException ("Unknown URI" +uri.tostring ());
}
return updatanum;
}

/**
* Delete operation:
* There are two possible deletions: deleting a table or deleting a piece of data
* The principle of deleting a piece of data is similar to querying a certain data, see below.
*/
@Override
public int Delete (URI Uri, String selection, string[] Selectionargs) {
Sqlitedatabase db=dbopenhelper.getwritabledatabase ();
int deletednum=0;
Switch (Uri_matcher.match (URI)) {
Delete Table
Case PERSONS:
Deletednum=db.delete ("Person", selection, Selectionargs);
Break
Delete a piece of data by ID
Case Person:
Long Id=contenturis.parseid (URI);
String where= "personid=" +ID;
if (selection!=null&&! "". Equals (Selection.trim ())) {
where=selection+ "and" +where;
}
Deletednum=db.delete ("Person", where, Selectionargs);
Break
Default
throw new IllegalArgumentException ("Unknown URI" +uri.tostring ());
}
return deletednum;
}
/**
* Query operation:
* There are two possibilities for query operations: Querying a table or querying a particular piece of data
* Precautions:
* Be careful when querying for a particular data--because this is the PersonID to query
* A piece of data, but there may be other restrictions. For example:
* Requires PersonID to be 2 and name is Xiaoming1
* So the query is divided into two steps:
* First step:
* Parse out PersonID put in where query condition
* Part II:
* To determine if there are other restrictions (such as name), and if so, to
* Group spelling to where query conditions.
* Detailed code see below.
*/
@Override
Public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, string sortOrder) {
Sqlitedatabase db=dbopenhelper.getwritabledatabase ();
Cursor Cursor;
Switch (Uri_matcher.match (URI)) {
Query table
Case PERSONS:
Cursor=db.query ("person", projection, selection, Selectionargs, NULL, NULL, sortOrder);
Break
Query for a piece of data by ID
Case Person:
First step:
Long Id=contenturis.parseid (URI);
String where= "personid=" +ID;
Step Two:
if (selection!=null&&! "". Equals (Selection.trim ())) {
where=selection+ "and" +where;
}
Cursor=db.query ("person", projection, where, Selectionargs, NULL, NULL, sortOrder);
Break
Default
throw new IllegalArgumentException ("Unknown URI" +uri.tostring ());
}
return cursor;
}

/**
* Returns the MIME type of the data represented by the current URI.
* If the URI corresponding to the data may contain more than one record, then return
* The string should start with "vnd.android.cursor.dir/"
* If the URI corresponds to the data that contains only one record, then return
* The string should start with "vnd.android.cursor.item/"
*/
@Override
Public String GetType (Uri uri) {
Switch (Uri_matcher.match (URI)) {
Case PERSONS:
return "Vnd.android.cursor.dir/persons";
Case Person:
return "Vnd.android.cursor.item/person";
Default
throw new IllegalArgumentException ("Unknown URI" +uri.tostring ());
}
}
}

Dbopenhelper is as follows:
Copy Code code as follows:

Package cn.testcontentprovider;
Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;
Import Android.database.sqlite.SQLiteOpenHelper;
public class Dbopenhelper extends Sqliteopenhelper {
Public Dbopenhelper {
Super (context, "contentprovidertest.db", NULL, 1);
}
@Override
public void OnCreate (Sqlitedatabase db) {
Db.execsql ("CREATE TABLE Person" (PersonID integer PRIMARY key autoincrement,name varchar (), phone varchar (), salary Integer (12)) ");
}
Call this method when the database version number is changed
@Override
public void Onupgrade (sqlitedatabase db, int arg1, int arg2) {
Db.execsql ("ALTER TABLE person ADD phone varchar () NULL");
Db.execsql ("ALTER TABLE person ADD salary Integer NULL");
}
}

Androidmanifest.xml is as follows:
Copy Code code as follows:

<?xml version= "1.0" encoding= "Utf-8"?>
<manifest xmlns:android= "Http://schemas.android.com/apk/res/android"
Package= "Cn.testcontentprovider"
Android:versioncode= "1"
Android:versionname= "1.0" >
<uses-sdk
Android:minsdkversion= "8"
android:targetsdkversion= "8"/>
<uses-permission android:name= "Android.permission.INTERNET"/>
<uses-permission android:name= "Android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name= "Android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>
<application
Android:allowbackup= "true"
android:icon= "@drawable/ic_launcher"
Android:label= "@string/app_name"
Android:theme= "@style/apptheme" >
<activity
Android:name= "Cn.testcontentprovider.MainActivity"
Android:label= "@string/app_name" >
<intent-filter>
<action android:name= "Android.intent.action.MAIN"/>
<category android:name= "Android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<provider
Android:name= "Cn.testcontentprovider.ContentProviderTest"
Android:authorities= "Cn.bs.testcontentprovider"
Android:exported= "true"
/>
</application>
</manifest>

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.