Examples explain how to use ContentProvider components in Android _android

Source: Internet
Author: User
Tags sqlite stub

ContentProvider Basic Use
to exchange data between applications, Android provides a standard API for data interchange between different applications, and when an application needs to expose its own data to other programs, Contentprovider,contentprovider The application can be implemented by providing ContentProvider, and other applications can manipulate contentprovider exposed data through contentresolver.

Steps to implement ContentProvider:

1 Write a class, inherit ContentProvider, and rewrite the Crud method inside.

2 Register the provider in the Androidmanifest.xml file.

Registering provider in Androidmanifest.xml requires the following 3 properties:

The implementation class of the Android:name provider.

The URI of the android:authorities provider.

Android:exported provider is exposed to other programs.


Contentresovler operation ContentProvider:

1 The Contentresolver,getcontentresovler () method is obtained from Contextwrapper, so it can be used in both activity and service.

2 invokes the Curd method and invokes the specified ContentProvider method via the parameter URL.


Here is a demo that inserts a piece of data into the ContentProvider and returns it to the ListView.

Main.xml:

<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 "
  tools:context= ". Main ">
 
  <listview
    android:id=" @+id/listview "
    android:layout_width=" Match_parent "
    android: layout_height= "Wrap_content"/>
 
</RelativeLayout>

Mysqliteopenhelper class

Package Com.app.dao;
 
Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;
Import android.database.sqlite.SQLiteDatabase.CursorFactory;
Import Android.database.sqlite.SQLiteOpenHelper;
 
public class Mysqliteopenhelper extends Sqliteopenhelper {public
 
  Mysqliteopenhelper (context context, String name,< C7/>cursorfactory Factory, int version) {
    Super (context, name, Factory, version);
 
  }
 
  @Override public
  void OnCreate (Sqlitedatabase db) {
 
    String create_sql = "CREATE Table tb_test" (_id integer Prima Ry key Autoincrement,name,gender,age) ";
     
    Db.execsql (Create_sql);
  }
 
  @Override public
  void Onupgrade (sqlitedatabase db, int oldversion, int newversion) {
 
  }
 
}

Mycontentprovider class

Package Com.app.dao;
Import Android.content.ContentProvider;
Import android.content.ContentValues;
Import Android.database.Cursor;
 
Import Android.net.Uri;
  public class Mycontentprovider extends contentprovider{mysqliteopenhelper helper=null;
  @Override public int Delete (Uri arg0, String arg1, string[] arg2) {return 0;
  @Override public String GetType (Uri arg0) {//TODO auto-generated method stub return null; @Override public URI Insert (URI arg0, contentvalues values) {String insert_sql= ' insert into Tb_test val
     
    UEs (null, ' wx ', ' Boy ', 17) ";
     
    Helper.getreadabledatabase (). Execsql (Insert_sql);
  return null; @Override public boolean onCreate () {helper=new mysqliteopenhelper (This.getcontext (), TEST.DB3, null,1)
     
    ;
  return true;
     
    @Override public Cursor query (Uri arg0, string[] arg1, String arg2, string[] arg3, string arg4) { String query_sql= "SELECT * from Tb_test";
     
    Cursor cursor=helper.getreadabledatabase (). Rawquery (Query_sql, NULL);
  return cursor;  @Override public int Update (Uri arg0, contentvalues arg1, String arg2, string[] arg3) {//TODO auto-generated
  Method stub return 0;
 }
 
}

ListView Display Interface Show.xml

<?xml version= "1.0" encoding= "Utf-8"?> <linearlayout xmlns:android=
"http://schemas.android.com/apk/" Res/android "
  android:layout_width=" match_parent "
  android:layout_height=" match_parent "
  android:o" rientation= "Horizontal" >
 
  <textview
    android:id= "@+id/name" android:layout_width= "Wrap_content"
    "
    android:layout_height=" wrap_content "/>
 
  <textview
    android:id=" @+id/gender "
    android: Layout_width= "Wrap_content"
    android:layout_height= "wrap_content"
    android:layout_marginleft= "60DP"/ >
 
  <textview
    android:id= "@+id/age"
    android:layout_width= "wrap_content"
    android:layout _height= "Wrap_content"
    android:layout_marginleft= "60DP"/>
 
</LinearLayout>

Main.java

Package com.app.main;
Import Android.annotation.SuppressLint;
Import android.app.Activity;
Import Android.content.ContentResolver;
Import Android.database.Cursor;
Import Android.net.Uri;
Import Android.os.Bundle;
Import Android.support.v4.widget.CursorAdapter;
Import Android.widget.ListView;
 
Import Android.widget.SimpleCursorAdapter;
 
  public class Main extends activity {Contentresolver resolver = null;
 
  ListView LV = null; @SuppressLint ("Newapi") @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (Savedinsta
 
    Ncestate);
 
    Setcontentview (R.layout.main);
 
    LV = (ListView) This.findviewbyid (R.id.listview);
 
    Resolver = This.getcontentresolver ();
 
    String str = "content://com.app.test.db/";
 
    Uri uri = uri.parse (str);
 
    Resolver.insert (URI, NULL);
 
    Cursor Cursor = resolver.query (URI, NULL, NULL, NULL, NULL);
        Simplecursoradapter adapter = new Simplecursoradapter (this, r.layout.show, cursor,New string[] {"Name", "Gender", "Age"}, new int[] {r.id.name, R.id.gender, r.id.age}, Cursoradapte
 
    R.flag_register_content_observer);
 
  Lv.setadapter (adapter);
 }
 
}

Implementation effect: (after 3 insert effects performed)

Unit Test for ContentProvider
ContentProvider is one of the four components of Android, and it's best to add unit tests when writing code, which will determine the correct crud to the data. This article mainly introduces the use of two main auxiliary classes in ContentProvider and the use of unit tests in ContentProvider.

Two auxiliary classes that need to be used: the Urimatcher class and the Contenturis class.

Urimatcher class: The ability to match the input URI parameters to determine what table to perform.

Contenturis class: Some methods need to return a URI, which makes it easy to generate URI classes.

For unit testing, it is very necessary for the individual to use the code in the future, so that it can be very accurate to determine the correctness of the code.

To use unit tests:

1 Add instrumentation, this part of the code is fixed, can also be completely in the ADT provided by the wizard to import.

<instrumentation
    android:name= "Android.test.InstrumentationTestRunner"
    android:targetpackage= " Com.example.android_contentprovider ">
  </instrumentation>

2 add <uses-library> This part of the code is also a fixed wording.

 <uses-library android:name= "Android.test.runner"/>


Well, the necessary knowledge has been finished, now on the code:

1 Generate a Sqlitedatabase class, this is the required class Mysqliteopenhelper class

Package com.app.db;
 
Import Android.content.Context;
Import Android.database.sqlite.SQLiteDatabase;
Import android.database.sqlite.SQLiteDatabase.CursorFactory;
Import Android.database.sqlite.SQLiteOpenHelper;
 
public class Mysqliteopenhelper extends Sqliteopenhelper {
 
  private static String db_name = "TEST.DB3";
  private static int VERSION = 1;
 
  Public Mysqliteopenhelper {
    Super (context, db_name, NULL, VERSION);
 
  }
 
  @Override public
  void OnCreate (Sqlitedatabase db) {
       //Build Table statement
    String create_student = ' CREATE TABLE student (_id Integer PRIMARY key autoincrement,name varchar (), age Integer,gender Vachar) ";
     
    Db.execsql (create_student);
       Never execute this sentence  //Db.close ();
 
  }
 
  @Override public
  void Onupgrade (sqlitedatabase arg0, int arg1, int arg2) {
 
  }
 
}


Then add the Mycontentprovider class we need:

Package com.app.contentprovider;
 
Import Com.app.db.MySQLiteOpenHelper;
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;
 
Import Android.util.Log;
 
  public class Mycontentprovider extends ContentProvider {mysqliteopenhelper helper = null;
 
  private static Urimatcher Matcher = new Urimatcher (urimatcher.no_match);
  Match a single record private static final int student = 1;
 
  Match more than one record private static final int students = 2;
 
    static {Matcher.adduri ("com.app.wx", "student/#", student);
  Matcher.adduri ("Com.app.wx", "student", students); @Override public int Delete (URI Uri, String selection, string[] selectionargs) {sqlitedatabase db = helper.
 
    Getwritabledatabase ();
 
    int action = Matcher.match (URI); Switch (action) {//Match single record case sTudent:long id = contenturis.parseid (URI);
 
      Gets the ID number String delete_id = "_id=" + ID of a single record;
      if (selection!= null) {delete_id + = delete_id + "and" + selection;
 
      } db.delete ("Student", delete_id, Selectionargs);
       
    Break
 
      Match multiple records case Students:db.delete ("Student", selection, Selectionargs);
    Break
  return 0;
    This method must be implemented, which is related to intent, and later @Override public String getType (URI uri) {int code = Matcher.match (URI);
    Switch (code) {case Student:return "Vnd.android.cursor.item/student_item";
    Case Students:return "Vnd.android.cursor.dir/students";
    Default:return null; @Override public Uri Insert (URI uri, contentvalues values) {sqlitedatabase db = Helper.getwritabledatab
 
    ASE ();
 
    int action = Matcher.match (URI);
 
Switch (action) {case Students:long id1 = Db.insert ("Student", "_id", values);      LOG.I ("--------", Contenturis.withappendedid (URI, ID1). toString ());
 
    Return Contenturis.withappendedid (URI, ID1);
  return null;
 
    @Override public boolean onCreate () {helper = new Mysqliteopenhelper (This.getcontext ());
  return true;  @Override public Cursor query (URI uri, string[] projection, string selection, string[] Selectionargs, string
 
    by) {Sqlitedatabase db = Helper.getwritabledatabase ();
 
    Cursor Cursor = null;
 
    int action = Matcher.match (URI);
          Switch (action) {Case students:cursor = db.query ("Student", projection, selection, Selectionargs,
 
      NULL, NULL, by-by);
 
    Break
 
    } System.out.println ("-----------count:" + cursor.getcount ());
  return cursor; @Override public int update (URI uri, contentvalues values, String selection, string[] arg3) {int Coun
 
    t =-1;
 
    Sqlitedatabase db = Helper.getwritabledatabase (); int action = Matcher.match (URI);
 
      Switch (action) {case student://To process the update with an id = Contenturis.parseid (URI);
 
      String id_selection = "_id=" + ID;
 
      if (selection!= null &&!selection.equals ("")) {id_selection = Id_selection + "and" + values;
 
      Count = db.update ("Student", Values, Id_selection, ARG3);
 
      System.out.println ("----------count:" + count);
    Break
  return count;

 }
 
}

This class is very long, but the method of execution is the more common curd method, it is important to use the Urimatcher and Contenturis classes.

Then execute the Unit test class: Test

Package com.app.contentprovider;
Import Android.content.ContentResolver;
Import android.content.ContentValues;
Import Android.database.Cursor;
Import Android.net.Uri;
Import Android.test.AndroidTestCase;
 
Import Android.util.Log; public class Test extends Androidtestcase {public void Insert () {contentresolver resolver = This.getcontext ().
 
    Getcontentresolver ();
 
    String str = "Content://com.app.wx/student";
 
    Contentvalues values = new Contentvalues ();
 
    Values.put ("name", "Wzq");
 
    Values.put ("Age", 18);
 
    Values.put ("Gender", "Boy");
 
  Resolver.insert (Uri.parse (str), values);
 
    public void Update () {Contentresolver resolver = This.getcontext (). Getcontentresolver ();
 
    String str = "CONTENT://COM.APP.WX/STUDENT/2";
 
    Contentvalues values = new Contentvalues ();
 
    Values.put ("name", "haha");
 
  Resolver.update (Uri.parse (str), values, NULL, NULL); public void query () {contentresolver resolver = This.getcontExt (). Getcontentresolver ();
 
    String str = "Content://com.app.wx/student";
 
    Uri uri = uri.parse (str);
 
    Cursor Cursor = Resolver.query (URI, new string[] {"_id", "Name,age,gender"}, NULL, NULL, "_id desc");
  LOG.D ("------count", Cursor.getcount () + "");
 
    public void Delete () {Contentresolver resolver = This.getcontext (). Getcontentresolver ();
 
    String str = "CONTENT://COM.APP.WX/STUDENT/2";
 
    Uri uri = uri.parse (str);
 
  Long Id=resolver.delete (URI, NULL, NULL);

 }
 
}

After the Insert method was executed (three times):

After the Update method has been executed:

After you execute the Query method:

After the Delete method has been executed:

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.