当前位置: 移动技术网 > IT编程>移动开发>Android > 实例解析Android系统中的ContentProvider组件用法

实例解析Android系统中的ContentProvider组件用法

2019年07月24日  | 移动技术网IT编程  | 我要评论

房贷基准利率2015,可口网,免费英语学习资料

contentprovider为android四大组件之一,主要用来应用程序之间的数据共享,也就是说一个应用程序用contentprovider将自己的数据暴露出来,其他应用程序通过contentresolver来对其暴露出来的数据进行增删改查。
contenprovider与contentresolver之间的对话同过uri(通用资源标识符),一个不恰当的比喻就好像浏览器要显示一个网页要有一个东西发送请求,这相当于contentresolver,你要拿东西就要知道去哪里拿,你就得知道服务器的域名或网址,而这个网址就相当于uri,当到达服务器的时候服务器要有个东西来处理,这就相当于contenprovider。

a程序通过contenprovider来暴露数据的基本步骤:
1、实现一个contenprovider的子类,并重写query,insert,update,delete等这几个方法,
2、在androidmanifest.xml中注册contenprovider,指定的android:authorities属性
b程序通过contentresolver来操作a程序暴露出来的数据的基本步骤
1、通过content的getcontentresolver()来获取contentresolver对象
2、通过contentresolver对象来query,insert,update,delete来进行操作
在实现query,insert,update,delete时有一个重要的参数uri类,uri一个中要的方法uri.parse(string str)用来解析str字符串,而str字符串格式一般都有a程序提供给b程序,b程序按照指定的格式去请求 。比如:content//:com.android.xiong.conentprovidertesta.firstcontentprovider/xiong 其格式一般分为三个部分:content//:这部分是固定不变的 而com.android.xiong.conentprovidertesta.firstcontentprovider表a程序在androidmanifest.xml注册的android:authorities属性,xiong则表示资源部分

<provider 
      android:name="com.android.xiong.conentprovidertesta.firstcontentprovider" 
      android:authorities="com.android.xiong.conentprovidertesta.firstcontentprovider" 
      android:exported="true" > 
</provider> 


实例如下

2016423110001350.jpg (408×454)

2016423110025072.jpg (399×620)

a程序:
userinfo.java

package com.android.xiong.conentprovidertesta; 
 
import android.content.contentprovider; 
import android.content.contentvalues; 
import android.content.urimatcher; 
import android.database.cursor; 
import android.database.sqlite.sqlitedatabase; 
import android.net.uri; 
 
public class firstcontentprovider extends contentprovider { 
 
  // urimatcher类主要用来匹配uri 
  private static final urimatcher urimatcher = new urimatcher( 
      urimatcher.no_match); 
  private mysqlite mysqlite; 
  static { 
    // 注册向外部程序提供的uri 
    urimatcher.adduri(userinfo.autor, "userinfo", 1); 
    urimatcher.adduri(userinfo.autor, "userinfoall", 2); 
  } 
  //删除数据 
  @override 
  public int delete(uri uri, string selection, string[] selectionargs) { 
    int number = 0; 
    if (urimatcher.match(uri) == 1) { 
      // 根据条件删除数据,并获取删除的行数 
      number = mysqlite.getreadabledatabase().delete("user_info", 
          selection, selectionargs); 
    } 
    // 通知数据已经改变 
    getcontext().getcontentresolver().notifychange(uri, null); 
    return number; 
  } 
 
  @override 
  public string gettype(uri uri) { 
 
    return null; 
  } 
  //插入数据 
  @override 
  public uri insert(uri uri, contentvalues values) { 
    string name = values.getasstring(userinfo.user.name).tostring(); 
    string age = values.getasinteger(userinfo.user.age).tostring(); 
    string maxid = "select max(id) id from user_info"; 
    cursor cursor = mysqlite.getreadabledatabase().rawquery(maxid, null); 
    cursor.movetofirst(); 
    int userid = cursor.getint(0) + 1; 
    if (urimatcher.match(uri) == 1) { 
 
      mysqlite.getwritabledatabase().execsql( 
          "insert into user_info values(?,?,?)", 
          new string[] { string.valueof(userid), name, age }); 
    } 
    return uri; 
  } 
 
  // 连接数据库 
  @override 
  public boolean oncreate() { 
    mysqlite = new mysqlite(getcontext(), "userinfo.db", null, 1); 
    return true; 
  } 
  //查询数据 
  @override 
  public cursor query(uri uri, string[] projection, string selection, 
      string[] selectionargs, string sortorder) { 
    sqlitedatabase sqlite = mysqlite.getreadabledatabase(); 
    string str = "select name,age from user_info"; 
    if (urimatcher.match(uri) == 1) { 
      str += " where " + selection; 
    } 
    cursor cursor = sqlite.rawquery(str, selectionargs); 
    return cursor; 
  } 
  //修改数据 
  @override 
  public int update(uri uri, contentvalues values, string selection, 
      string[] selectionargs) { 
    sqlitedatabase sqlite = mysqlite.getreadabledatabase(); 
    int number = 0; 
    if (urimatcher.match(uri) == 1) { 
      number = sqlite.update("user_info", values, selection, 
          selectionargs); 
    } 
    return number; 
  } 
 
} 

 
firstcontentprovider.java

package com.android.xiong.conentprovidertesta; 
 
import android.content.contentprovider; 
import android.content.contentvalues; 
import android.content.urimatcher; 
import android.database.cursor; 
import android.database.sqlite.sqlitedatabase; 
import android.net.uri; 
 
public class firstcontentprovider extends contentprovider { 
 
  // urimatcher类主要用来匹配uri 
  private static final urimatcher urimatcher = new urimatcher( 
      urimatcher.no_match); 
  private mysqlite mysqlite; 
  static { 
    // 注册向外部程序提供的uri 
    urimatcher.adduri(userinfo.autor, "userinfo", 1); 
    urimatcher.adduri(userinfo.autor, "userinfoall", 2); 
  } 
  //删除数据 
  @override 
  public int delete(uri uri, string selection, string[] selectionargs) { 
    int number = 0; 
    if (urimatcher.match(uri) == 1) { 
      // 根据条件删除数据,并获取删除的行数 
      number = mysqlite.getreadabledatabase().delete("user_info", 
          selection, selectionargs); 
    } 
    // 通知数据已经改变 
    getcontext().getcontentresolver().notifychange(uri, null); 
    return number; 
  } 
 
  @override 
  public string gettype(uri uri) { 
 
    return null; 
  } 
  //插入数据 
  @override 
  public uri insert(uri uri, contentvalues values) { 
    string name = values.getasstring(userinfo.user.name).tostring(); 
    string age = values.getasinteger(userinfo.user.age).tostring(); 
    string maxid = "select max(id) id from user_info"; 
    cursor cursor = mysqlite.getreadabledatabase().rawquery(maxid, null); 
    cursor.movetofirst(); 
    int userid = cursor.getint(0) + 1; 
    if (urimatcher.match(uri) == 1) { 
 
      mysqlite.getwritabledatabase().execsql( 
          "insert into user_info values(?,?,?)", 
          new string[] { string.valueof(userid), name, age }); 
    } 
    return uri; 
  } 
 
  // 连接数据库 
  @override 
  public boolean oncreate() { 
    mysqlite = new mysqlite(getcontext(), "userinfo.db", null, 1); 
    return true; 
  } 
  //查询数据 
  @override 
  public cursor query(uri uri, string[] projection, string selection, 
      string[] selectionargs, string sortorder) { 
    sqlitedatabase sqlite = mysqlite.getreadabledatabase(); 
    string str = "select name,age from user_info"; 
    if (urimatcher.match(uri) == 1) { 
      str += " where " + selection; 
    } 
    cursor cursor = sqlite.rawquery(str, selectionargs); 
    return cursor; 
  } 
  //修改数据 
  @override 
  public int update(uri uri, contentvalues values, string selection, 
      string[] selectionargs) { 
    sqlitedatabase sqlite = mysqlite.getreadabledatabase(); 
    int number = 0; 
    if (urimatcher.match(uri) == 1) { 
      number = sqlite.update("user_info", values, selection, 
          selectionargs); 
    } 
    return number; 
  } 
 
} 

mysqlite.java

package com.android.xiong.conentprovidertesta; 
 
import android.content.context; 
import android.database.sqlite.sqlitedatabase; 
import android.database.sqlite.sqlitedatabase.cursorfactory; 
import android.database.sqlite.sqliteopenhelper; 
 
public class mysqlite extends sqliteopenhelper { 
 
  static final string sql = "create table user_info(id int,name varchar(30),age int)"; 
 
  public mysqlite(context context, string name, cursorfactory factory, 
      int version) { 
    super(context, name, factory, version); 
    // todo auto-generated constructor stub 
  } 
 
  @override 
  public void oncreate(sqlitedatabase db) { 
    //创建数据表 
    db.execsql(sql); 
 
  } 
 
  @override 
  public void onupgrade(sqlitedatabase db, int oldversion, int newversion) { 
    // todo auto-generated method stub 
 
  } 
 
} 

mainactivity.java

package com.android.xiong.conentprovidertesta; 
 
import android.content.context; 
import android.database.sqlite.sqlitedatabase; 
import android.database.sqlite.sqlitedatabase.cursorfactory; 
import android.database.sqlite.sqliteopenhelper; 
 
public class mysqlite extends sqliteopenhelper { 
 
  static final string sql = "create table user_info(id int,name varchar(30),age int)"; 
 
  public mysqlite(context context, string name, cursorfactory factory, 
      int version) { 
    super(context, name, factory, version); 
    // todo auto-generated constructor stub 
  } 
 
  @override 
  public void oncreate(sqlitedatabase db) { 
    //创建数据表 
    db.execsql(sql); 
 
  } 
 
  @override 
  public void onupgrade(sqlitedatabase db, int oldversion, int newversion) { 
    // todo auto-generated method stub 
 
  } 
 
} 

activity_main.xml

<linearlayout 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" 
  android:orientation="vertical" 
  tools:context=".mainactivity" > 
 
  <textview 
    android:id="@+id/txt1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:gravity="center_horizontal" 
    android:text="添加信息" 
    android:textsize="20dp" /> 
 
  <edittext 
    android:id="@+id/ed1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:hint="添加name" /> 
 
  <edittext 
    android:id="@+id/ed2" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:hint="添加age" 
    android:inputtype="number" /> 
 
  <button 
    android:id="@+id/bt1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:text="提交数据" /> 
 
    <listview 
      android:id="@+id/lists" 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" > 
    </listview> 
 
 
</linearlayout> 

item.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/item_txt1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/> 
    <textview  
    android:id="@+id/item_txt2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/> 
   
 
</linearlayout> 

b程序
userinfo.java

package com.android.xiong.contentprovidertestb; 
 
//向外部程序提供一个工具类 
public class userinfo { 
 
  // 获取contentprovider的“域名” 
  public static final string autor = "com.android.xiong.conentprovidertesta.firstcontentprovider"; 
   
  //定义一个静态内部类,提供contentprovider可操作的列 
  public static final class user { 
     
    public static final string id="id"; 
    public static final string name="name"; 
    public static final string age="age"; 
    //定义该content提供服务的一个uri 
    public static final string uri="content://"+autor+"/userinfo"; 
    public static final string uriall="content://"+autor+"/userinfoall"; 
     
  } 
 
} 

mainactivity.java

package com.android.xiong.contentprovidertestb; 
 
import java.util.arraylist; 
import java.util.hashmap; 
import java.util.list; 
import java.util.map; 
 
import android.app.activity; 
import android.content.contentvalues; 
import android.database.cursor; 
import android.net.uri; 
import android.os.bundle; 
import android.view.menu; 
import android.view.view; 
import android.view.view.onclicklistener; 
import android.widget.button; 
import android.widget.edittext; 
import android.widget.listview; 
import android.widget.scrollview; 
import android.widget.simpleadapter; 
import android.widget.toast; 
 
public class mainactivity extends activity { 
 
  private button bt1, bt2, bt3, bt4; 
  private edittext ed1, ed2; 
  private listview list1; 
  private scrollview sc1; 
 
  @override 
  protected void oncreate(bundle savedinstancestate) { 
    super.oncreate(savedinstancestate); 
    setcontentview(r.layout.activity_main); 
    bt1 = (button) findviewbyid(r.id.bt1); 
    bt2 = (button) findviewbyid(r.id.bt2); 
    bt3 = (button) findviewbyid(r.id.bt3); 
    bt4 = (button) findviewbyid(r.id.bt4); 
    ed1 = (edittext) findviewbyid(r.id.ed1); 
    ed2 = (edittext) findviewbyid(r.id.ed2); 
    list1 = (listview) findviewbyid(r.id.list); 
    // 显示所有数据 
    list1.setadapter(adapter(0)); 
    sc1 = (scrollview) findviewbyid(r.id.scr1); 
    // 向添加contentprovidera应用的数据 
    bt1.setonclicklistener(new onclicklistener() { 
 
      @override 
      public void onclick(view v) { 
        string eds1 = ed1.gettext().tostring(); 
        string eds2 = ed2.gettext().tostring(); 
        contentvalues content = new contentvalues(); 
        if (!eds1.equals("") && !eds2.equals("")) { 
          content.put(userinfo.user.name, eds1); 
          content.put(userinfo.user.age, eds2); 
          mainactivity.this.getcontentresolver().insert( 
              uri.parse(userinfo.user.uri), content); 
          toast.maketext(mainactivity.this, "数据插入成功", 
              toast.length_long).show(); 
          // 刷新listview界面 
          list1.setadapter(adapter(0)); 
        } else { 
          toast.maketext(mainactivity.this, "name和age不能为空", 
              toast.length_long).show(); 
        } 
 
      } 
    }); 
    // 根据条件删除contentprovidera应用的数据 
    bt2.setonclicklistener(new onclicklistener() { 
 
      @override 
      public void onclick(view v) { 
        string eds1 = ed1.gettext().tostring(); 
        string eds2 = ed2.gettext().tostring(); 
        if (!eds1.equals("") || !eds2.equals("")) { 
          hashmap<string, string[]> wheres = wheres(eds1, eds2); 
          string sql = wheres.get("sql")[0]; 
          string[] selectags = wheres.get("selectages"); 
          mainactivity.this.getcontentresolver().delete( 
              uri.parse(userinfo.user.uri), sql, selectags); 
 
        } else { 
          toast.maketext(mainactivity.this, "请输入删除条件", 
              toast.length_long).show(); 
        } 
        // 刷新listview界面 
        list1.setadapter(adapter(0)); 
      } 
    }); 
    // 修改数据 
    bt3.setonclicklistener(new onclicklistener() { 
 
      @override 
      public void onclick(view v) { 
        string eds1 = ed1.gettext().tostring(); 
        string eds2 = ed2.gettext().tostring(); 
        contentvalues values = new contentvalues(); 
        // 根据条件将列修改为xiong,23 
        values.put(userinfo.user.name, "xiong"); 
        values.put(userinfo.user.age, "23"); 
        if (!eds1.equals("") || !eds2.equals("")) { 
          hashmap<string, string[]> wheres = wheres(eds1, eds2); 
          string sql = wheres.get("sql")[0]; 
          string[] selectags = wheres.get("selectages"); 
          int i=mainactivity.this.getcontentresolver().update( 
              uri.parse(userinfo.user.uri), values, sql, 
              selectags); 
 
        } else { 
          toast.maketext(mainactivity.this, "请输入删除条件", 
              toast.length_long).show(); 
        } 
        // 刷新listview界面 
        list1.setadapter(adapter(0)); 
 
      } 
    }); 
    // 根据条件查询contentprovidera应用的数据 
    bt4.setonclicklistener(new onclicklistener() { 
      @override 
      public void onclick(view v) { 
        if (!ed1.gettext().tostring().equals("") 
            || !ed2.gettext().tostring().equals("")) 
          list1.setadapter(adapter(1)); 
        else 
          list1.setadapter(adapter(0)); 
      } 
    }); 
  } 
 
  // 用来判别条件 
  public hashmap<string, string[]> wheres(string eds1, string eds2) { 
    hashmap<string, string[]> where = new hashmap<string, string[]>(); 
    if (!eds1.equals("") && !eds2.equals("")) { 
      string[] sql = { userinfo.user.name + "=? and " + userinfo.user.age 
          + " =?" }; 
      string[] selectages = { eds1, eds2 }; 
      where.put("sql", sql); 
      where.put("selectages", selectages); 
 
    } 
    if (!eds1.equals("") && eds2.equals("")) { 
      string[] sql = { userinfo.user.name + "=? " }; 
      string[] selectages = { eds1 }; 
      where.put("sql", sql); 
      where.put("selectages", selectages); 
 
    } 
    if (eds1.equals("") && !eds2.equals("")) { 
      string[] sql = { userinfo.user.age + " =?" }; 
      string[] selectages = { eds2 }; 
      where.put("sql", sql); 
      where.put("selectages", selectages); 
 
    } 
    return where; 
  } 
 
  // 用来显示数据 
  public simpleadapter adapter(int i) { 
    cursor cs = mainactivity.this.getcontentresolver().query( 
        uri.parse(userinfo.user.uriall), null, null, null, null); 
    string eds1 = ed1.gettext().tostring(); 
    string eds2 = ed2.gettext().tostring(); 
    if (i == 1) { 
      if (!eds1.equals("") || !eds2.equals("")) { 
        hashmap<string, string[]> wheres = wheres(eds1, eds2); 
        string sql = wheres.get("sql")[0]; 
        string[] selectags = wheres.get("selectages"); 
        cs = mainactivity.this.getcontentresolver().query( 
            uri.parse(userinfo.user.uri), null, sql, selectags, 
            null); 
      } 
 
    } 
 
    list<map<string, object>> lists = new arraylist<map<string, object>>(); 
    while (cs.movetonext()) { 
      map<string, object> map = new hashmap<string, object>(); 
      map.put("name", cs.getstring(0)); 
      map.put("age", cs.getstring(1)); 
      lists.add(map); 
    } 
    simpleadapter simepl = new simpleadapter(mainactivity.this, lists, 
        r.layout.item, new string[] { "name", "age" }, new int[] { 
            r.id.item_txt1, r.id.item_txt2 }); 
    return simepl; 
  } 
 
  @override 
  public boolean oncreateoptionsmenu(menu menu) { 
    // inflate the menu; this adds items to the action bar if it is present. 
    getmenuinflater().inflate(r.menu.main, menu); 
    return true; 
  } 
 
} 

activity.xml

<linearlayout 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" 
  android:orientation="vertical" 
  tools:context=".mainactivity" > 
 
  <scrollview 
    android:id="@+id/scr1" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 
 
    <linearlayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="vertical" > 
 
      <button 
        android:id="@+id/bt1" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:text="添加" /> 
 
      <button 
        android:id="@+id/bt2" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:text="删除" /> 
 
      <button 
        android:id="@+id/bt3" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:text="更改" /> 
 
      <button 
        android:id="@+id/bt4" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:text="查询" /> 
 
      <edittext 
        android:id="@+id/ed1" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:hint="输入name条件进行增删改查" /> 
 
      <edittext 
        android:id="@+id/ed2" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:hint="输age条件进行增删改查" /> 
    </linearlayout> 
  </scrollview> 
 
  <listview 
    android:id="@+id/list" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" > 
  </listview> 
 
</linearlayout> 

 
item.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/item_txt1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/> 
    <textview  
    android:id="@+id/item_txt2" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/> 
   
 
</linearlayout> 


监听contentprovider数据改变
当程序a在执行insert、update、delete时,通过getcontext().getcontentresolver().notifychange(uri, null)方法来告诉所有注册在该uri的监听者数据发生改变

//删除数据 
  @override 
  public int delete(uri uri, string selection, string[] selectionargs) { 
    int number = 0; 
    if (urimatcher.match(uri) == 1) { 
      // 根据条件删除数据,并获取删除的行数 
      number = mysqlite.getreadabledatabase().delete("user_info", 
          selection, selectionargs); 
    } 
    // 通知数据已经改变 
    getcontext().getcontentresolver().notifychange(uri, null); 
    return number; 
  } 

 
在b程序通过registercontentobserver(uri uri,boolean notifyfordescendents, contentobserver observer)方法来监听a程序的数据改变

@override 
protected void oncreate(bundle savedinstancestate) { 
  super.oncreate(savedinstancestate); 
  setcontentview(r.layout.activity_main); 
  // 为uri的数据改变注册监听器 
  getcontentresolver().registercontentobserver( 
      uri.parse("content://com.android.xiong.conentprovidertesta.firstcontentprovider/userinfo"), true, 
      new smsobserver(new handler())); 
} 

registercontentobserver中第三个参数为监听实例 ,需要通过继承contentobserver类,并重写onchange(booleab selfchange)方法,该方法在监听uri的contentprovider的数据发生改变时触发该方法

// 提供方自定义的contentoberver监听器 
private final class observer extends contentobserver { 
 
  public smsobserver(handler handler) { 
    super(handler); 
  } 
 
  @override 
  public void onchange(boolean selfchange, uri uri) { 
 
    // 查询发送邮箱中的短息(处于正在发送状态的短信放在发送箱) 
    cursor cursor = getcontentresolver().query( 
        uri.parse("content://com.android.xiong.conentprovidertesta.firstcontentprovider/userinfo"), null, null, null, null); 
    } 
  } 
 
} 

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网