1ContentProvider Related knowledge
1.1 In the Android application, through the file way to share the data, the file operation needs to read and write data, the use of sharedpreferences shared data, need to use the Sharedpreferences API to read and write data. It can be seen that although they can share data externally, the way data is accessed varies depending on how the data is stored.
Using ContentProvider shared data in Android to share data between different applications, the underlying operation is transparent, provides a unified interface externally, and allows other applications to easily access the data.
1.2ContentProvider uses the form of tables to organize the data, regardless of the source of the data, it will be considered a table, and then the data organized into a table. It also provides operations such as query, INSERT, UPDATE (update), delete (delete), get data type (GetType), and callback function (OnCreate) that is called when data is created. In addition, each contentprovider has a common URI, which is used to represent the data provided by this contentprovider. The ContentProvider provided by Android are stored in the Android.provider package.
2 Code
2.1 Accessing contacts in the system
public class Mainactivity extends Activity {private ListView listview = null; @Overrideprotected void OnCreate (Bundle saved Instancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); listview = (ListView) This.findviewbyid (R.id.listview);//Query the system for all contact URI URIs = uri.parse ("content://com.android.contacts/contacts"); cursor cursor = getcontentresolver (). Query (URI, NULL, NULL, NULL, or null);// Create a Simplecursoradapter object based on the cursor simplecursoradapter simplecursoradapter = new Simplecursoradapter (this,android. R.layout.simple_list_item_1, Cursor,new string[] {ContactsContract.Contacts.DISPLAY_NAME},new int[] {Android. R.id.text1},cursoradapter.flag_register_content_observer);//Display the contact list in the ListView Listview.setadapter ( Simplecursoradapter);}}
You also need to add a request to the manifest file to access the communication license
<uses-permission android:name= "Android.permission.READ_CONTACTS"/>
2.2 Content Provider of the program
This example is the operation of the database implementation, the operation of the database is the content of the previous article
Database Operations Classes
public class Dbopenhelper extends Sqliteopenhelper {public Dbopenhelper (context context) {/** * postgrade.db database name; null Indicates that the default cursor factory is used, 1 is the first version, the recommended setting is 1 */super (context, "postgrade.db", NULL, 1);} @Overridepublic void OnCreate (Sqlitedatabase db) {//This method is called the first time the database is created//so operations such as tables can be created in this place Db.execsql ("CREATE table Student (ID INTEGER PRIMARY KEY autoincrement, name VARCHAR (20)) "); @Overridepublic void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {//Modify the version of the database will trigger this function// Here you can add a new table or modify the table's Fields}}
Custom content Provider
public class Stuprovider extends ContentProvider {private Dbopenhelper dbopenhelper = null;private static final Urimatcher matcher;private static final int STU = 0;//Match succeeded return value private static final String authority;//domain name [hostname]private static final String student;//path name static {//when mismatched, returns-1, i.e. Urimatcher.no_matchmatcher = new Urimatcher (urimatcher.no_match); authority = "Org.tonny.providers.stuprovider"; STUDENT = "STUDENT"; Matcher.adduri (authority, STUDENT, STU);} @Overridepublic Boolean onCreate () {//is called only once when the instance is created, Dbopenhelper = new Dbopenhelper (GetContext ()) as the initialization operation for the data; return false;} @Overridepublic String getType (Uri uri) {//Returns the content type of the data currently being manipulated, such as txt-->plain/text html-->html/textreturn null;} @Overridepublic uri insert (URI uri, contentvalues values) {//Allow external apps to insert data into the content provider Sqlitedatabase db = Dbopenhelper.getwritabledatabase (); switch (Matcher.match (URI)) {case stu://uses its own method, the second is the column name long rowId when inserting null values = Db.insert ("student", null, values); Uri Inserturi = Contenturis.withappendedid (uri, ROWID);//can also be used in this way//Uri Inserturi =//uri.parse ("content://org.tonny.test.providers.stuprovider/student/" +//rowId); return Inserturi;default:throw New IllegalArgumentException ("This was an unknown URI:" + uri);}} @Overridepublic int Delete (URI Uri, String selection, string[] Selectionargs) {//TODO auto-generated method Stubreturn 0; } @Overridepublic int update (URI uri, contentvalues values, String selection,string[] selectionargs) {//TODO Auto-generat Ed method Stubreturn 0;} @Overridepublic Cursor query (Uri uri, string[] projection, string selection,string[] Selectionargs, string sortOrder) {// TODO auto-generated method Stubreturn null;}}
Model Layer
Package Org.tonny.domain;public class Student {private int id;private String name;public Student () {}public Student (int ID , String name) {this.id = Id;this.name = name;} public int getId () {return ID;} public void setId (int id) {this.id = ID;} Public String GetName () {return name;} public void SetName (String name) {this.name = name;}}
Table-related operations
public class Studentservice {private Dbopenhelper dbhelper = Null;public Studentservice (context context) {This.dbhelper = New Dbopenhelper (context);} public void Insert (Student stu) {//internal cache function, using the same handle, if the database is full, returns a read-only handle sqlitedatabase db = Dbhelper.getwritabledatabase ();//Use placeholder '? ' to prevent special characters db.execsql ("INSERT into student VALUES (?,?)", new object[] { Stu.getid (), Stu.getname ()}); public void Delete (Integer id) {Sqlitedatabase db = Dbhelper.getreadabledatabase ();d b.execsql ("Delete from student WHERE id =? ", new string[] {string.valueof (ID)});} public void Update (Student stu) {sqlitedatabase db = Dbhelper.getwritabledatabase ();d b.execsql ("update Student SET name = ? WHERE id =? ", new string[] {stu.getname (), String.valueof (Stu.getid ())});} Public Student query (Integer ID) {Sqlitedatabase db = Dbhelper.getreadabledatabase (); String sql = "SELECT * FROM student WHERE id =?"; cursor cursor = db.rawquery (sql, new string[] {string.valueof (ID)}), if (Cursor.movetofirst ()) {int stuid = cursor.GetInt (Cursor.getcolumnindex ("id")); String stuname = cursor.getstring (Cursor.getcolumnindex ("name")), return new Student (Stuid, stuname);} return null;}}
Activity actions
public class Mainactivity extends Activity {private EditText _txtid = null;private EditText _txtname = null;private Studen TService _service = null, @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate ( Savedinstancestate); Setcontentview (r.layout.activity_main); _txtid = (EditText) This.findviewbyid (R.id.txtId); _ Txtname = (EditText) This.findviewbyid (r.id.txtname); _service = new Studentservice (Getapplicationcontext ());} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} public void Onbtnok (View v) {int id = integer.valueof (_txtid.gettext (). toString ()); String name = _txtname.gettext (). toString (); Student stu = new Student (ID, name); _service.insert (Stu);}}
Description of the URI in the manifest file
<provider android:name= "Org.tonny.db.StuProvider" android:authorities= " Org.tonny.providers.stuprovider " android:exported=" true " tools:ignore=" Exportedcontentprovider "/>
3. Summary
To this day, it feels like it's time to find some business research.
Android Learning five: Content Provider use