实例讲解Android中ContentProvider组件的使用方法

实例讲解Android中ContentProvider组件的使用方法,第1张

概述ContentProvider基本使用为了在应用程序之间交换数据,android提供了ContentProvider,ContentProvider是不同应用程序之间进行数据交换的标准API,当一个应用程序需要把自己的数据暴露给其他程序使用时,该应用程序

ContentProvIDer基本使用
为了在应用程序之间交换数据,androID提供了ContentProvIDer,ContentProvIDer是不同应用程序之间进行数据交换的标准API,当一个应用程序需要把自己的数据暴露给其他程序使用时,该应用程序就可以通过提供ContentPRovIDer来实现,其他应用程序就可以通过ContentResolver来 *** 作ContentProvIDer暴露的数据。

实现ContentProvIDer的步骤:

1)编写一个类,继承ContentProvIDer,并且重写里面的CRUD方法。

2)在androIDmanifest.xml文件中注册provIDer。

在androIDmanifest.xml中注册provIDer需要以下3个属性:

             androID:name              provIDer的实现类。

             androID:authoritIEs       provIDer的uri。

             androID:exported          provIDer是否暴露给其他程序。


ContentResovler *** 作ContentProvIDer:

1)获取ContentResolver,getContentResovler()方法来自于Contextwrapper,所以activity和service中都可以使用。

2)调用CURD方法,通过参数url,调用指定的ContentProvIDer的方法。


下面是一个demo,向contentProvIDer中插入一条数据,并且返回到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类

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,CursorFactory factory,int version) {    super(context,name,factory,version);   }   @OverrIDe  public voID onCreate(sqliteDatabase db) {     String create_sql = "create table tb_test(_ID integer primary key autoincrement,gender,age)";         db.execsql(create_sql);  }   @OverrIDe  public voID onUpgrade(sqliteDatabase db,int oldVersion,int newVersion) {   } }

MyContentProvIDer类

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 values(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[] arg3) {    // Todo auto-generated method stub    return 0;  } }

ListvIEw的显示界面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:orIEntation="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(savedInstanceState);     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);     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 },CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);     lv.setAdapter(adapter);   } }

实现效果:(执行了3次插入后的效果)

ContentProvIDer的单元测试
ContentProvIDer是androID的四大组件之一,在编写代码的时候最好是加上单元测试,这样可以确定对数据的CRUD的正确。本篇文章主要介绍ContentProvIDer中两个主要辅助类的使用还有单元测试的在ContentProvIDer中的使用。

需要用到的两个辅助类:UriMatcher类和ContentUris类。

UriMatcher类:能够对输入的uri参数就行匹配,以确定对什么表执行什么样的 *** 作。

ContentUris类:有些方法需要返回uri,运用此类可以方便的生成uri类。

对于单元测试,个人觉得非常有必要在今后写代码的时候使用,这样可以非常准确的确定代码的正确性。

使用单元测试的步骤:

 1)加入instrumentation,这个部分的代码是固定,也可以完全在ADT提供的向导中导入。

<instrumentation    androID:name="androID.test.InstrumentationTestRunner"    androID:targetPackage="com.example.androID_contentprovIDer" >  </instrumentation>

2)添加<uses-library>,这个部分的代码也是固定的写法。

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


好了,必备的知识已经讲完了,现在上代码:

1)生成一个sqliteDatabase类,这个是必需的类MysqLiteOpenHelper类

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(Context context) {    super(context,DB_name,VERSION);   }   @OverrIDe  public voID onCreate(sqliteDatabase db) {       //建表语句    String create_student = "create table student(_ID integer primary key autoincrement,name varchar(10),age integer,gender vachar(10))";         db.execsql(create_student);       //千万不能执行这句  // db.close();   }   @OverrIDe  public voID onUpgrade(sqliteDatabase arg0,int arg1,int arg2) {   } }

 
然后添加我们需要的MyContentProvIDer类:

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);   // 匹配单条记录  private static final int student = 1;  // 匹配多条记录  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) {         // 匹配单条记录    case student:       long ID = ContentUris.parseID(uri);     //获取单条记录的ID号      String delete_ID = "_ID=" + ID;       if (selection != null) {        delete_ID += delete_ID + " and " + selection;      }       db.delete("student",delete_ID,selectionArgs);       break;           // 匹配多条记录    case students:       db.delete("student",selection,selectionArgs);       break;    }         return 0;  }   //必需实现这个方法,这个方法与intent有关系,以后再讲  @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.getWritableDatabase();     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[] selectionArgs,String orderBy) {     sqliteDatabase db = helper.getWritableDatabase();     Cursor cursor = null;     int action = matcher.match(uri);     switch (action) {     case students:       cursor = db.query("student",projection,selectionArgs,orderBy);       break;     }     System.out.println("-----------count:" + cursor.getCount());     return cursor;  }   @OverrIDe  public int update(Uri uri,ContentValues values,String[] arg3) {     int count = -1;     sqliteDatabase db = helper.getWritableDatabase();     int action = matcher.match(uri);     switch (action) {     case student:      // 以ID来处理更新      long 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;  } }

这个类很长,但是执行的方法都是比较常见的CURD的方法,重要的是UriMatcher和ContentUris类的使用。

接着执行单元测试类: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","哈哈");     resolver.update(Uri.parse(str),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" },"_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);   } }

执行insert方法之后(执行了三次):

执行了update方法之后:

执行了query方法之后:

执行了delete方法之后:

总结

以上是内存溢出为你收集整理的实例讲解Android中ContentProvider组件的使用方法全部内容,希望文章能够帮你解决实例讲解Android中ContentProvider组件的使用方法所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1141995.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存