当前位置: 移动技术网 > IT编程>移动开发>Android > Android数据持久化之ContentProvider机制详解

Android数据持久化之ContentProvider机制详解

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

推倒小萝莉游戏,7474,和平饭店剧情分集介绍

本文实例讲述了android数据持久化之contentprovider机制。分享给大家供大家参考,具体如下:

一般而言,android操作系统的应用程序所建立的数据只允许自己使用,应用程序彼此间无法借助公用存储器来共享数据,android系统提供了一个机制,即内容提供器(contentprovider),来公开自己私有的数据到数据内容器,通过该机制,可以供其他应用程序来读取自己内部的数据,当然也可以访问其他应用程序的数据。通常,内容提供器背后都有sqlite数据库的支持,用以存储内容提供内部数据。

实现contentprovider与实现sqlite的区别:

应用程序实现sqlite时,由应用程序直接与数据库进行对接,所以要在应用程序中实现sqlite的接口:db.oncreate()、db.insert()、db.update()、db.delete()、db.query()和db.close();

实现内容提供器时,在应用程序与数据库之间要实现一个contentprovider程序,这个contentprovider程序会直接与数据库进行对接,此时应用程序需要实现和contentprovider程序接口的方法。

下面该说说如何建立内容提供器了:

首先,实现内容提供器接口:

实现该接口的5个重要方法;

其次,定义数据uri:

提供器应用程序需要定义一个“基底”uri,以供其他应用程序访问这一内容提供器,这一个uri必须是唯一的,且必须是以“content://”开头,content:   表示内容提供器程序所控制数据的位置;在androidmanifest.xml配置文件中添加如下代码以进行声明:

<!-- 设置类名和授权 multiprocess属性是数据的同步性(同一时间可能有多个程序访问该内容提供器)-->
<provider
  android:name="contentproviderclass"
  android:multiprocess="true"
  android:authorities="com.example.data_contentprovider.contentproviderclass" >
</provider>

在应用程序中添加如下代码:

//acquire the uri of contentprovider
getintent().setdata(uri.parse("content://com.example.data_contentprovider.contentproviderclass"));
uri uri = getintent().getdata();

定义一个uri所在的位置,并设置一个变量来找到内容提供器程序的接口;

如下是一个完整的代码,功能是实现内容提供器的建立以及通过该内容提供器程序来添加和检索数据:

实现内容提供器接口的代码:

package com.example.data_contentprovider;
import com.example.data_contentprovider.db.dbhelper;
import android.net.uri;
import android.content.contentprovider;
import android.content.contentvalues;
import android.database.cursor;
import android.database.sqlite.sqlitedatabase;
import android.database.sqlite.sqlitequerybuilder;
public class contentproviderclass extends contentprovider {
  dbhelper databasehelper; // 定义databasehelper类变量databasehelper
  // 实现contentprovider的oncreate方法
  @override
  public boolean oncreate() {
    // todo auto-generated method stub
    databasehelper = new dbhelper(getcontext());
    return true;
  }
  @override
  public uri insert(uri uri, contentvalues values) {
    // todo auto-generated method stub
    sqlitedatabase db = databasehelper.getwritabledatabase();
    db.insert("test", null, values);
    return null;
  }
  @override
  public cursor query(uri uri, string[] projection, string selection,
      string[] selectionargs, string sortorder) {
    // todo auto-generated method stub
    sqlitedatabase db = databasehelper.getreadabledatabase();
    sqlitequerybuilder querybuilder = new sqlitequerybuilder();
    querybuilder.settables("test");
    cursor cursor = querybuilder.query(db, projection, selection,
        selectionargs, null, null, null);
    return cursor;
  }
  @override
  public int delete(uri uri, string selection, string[] selectionargs) {
    // todo auto-generated method stub
    return 0;
  }
  @override
  public string gettype(uri uri) {
    // todo auto-generated method stub
    return null;
  }
  @override
  public int update(uri uri, contentvalues values, string selection,
      string[] selectionargs) {
    // todo auto-generated method stub
    return 0;
  }
}

配置androidmanifest.xml文件:

<!-- 设置类名和授权 multiprocess属性是数据的同步性(同一时间可能有多个程序访问该内容提供器)-->
<provider
  android:name="contentproviderclass"
  android:multiprocess="true"
  android:authorities="com.example.data_contentprovider.contentproviderclass" >
</provider>

建立一个sqlite数据库系统来存储和管理数据,同时利用sqliteopenhilper类协助建立数据库和sqlitedatabase类来管理数据库:

package com.example.data_contentprovider.db;
import android.content.context;
import android.database.sqlite.sqlitedatabase;
import android.database.sqlite.sqliteopenhelper;
import android.provider.basecolumns;
public class dbhelper extends sqliteopenhelper {
  // 建立test.db数据库
  public dbhelper(context context) {
    super(context, "test.db", null, 1);
  }
  // 建立test表
  @override
  public void oncreate(sqlitedatabase db) {
    db.execsql("create table test (" + basecolumns._id
        + "integer primary key," + "name text," + "description text"
        + ");");
  }
  // 更新新版本
  @override
  public void onupgrade(sqlitedatabase db, int oldversion, int newversion) {
    db.execsql("drop table if exists test");
    oncreate(db);
  }
}

下面就是provider的应用程序了:

package com.example.data_contentprovider;
import java.util.arraylist;
import java.util.hashmap;
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.widget.listview;
import android.widget.simpleadapter;
public class contentprovideractivity extends activity {
  string [] from = {"column00","column01","column02"};
  @suppresswarnings("deprecation")
  @override
  protected void oncreate(bundle savedinstancestate) {
    // todo auto-generated method stub
    super.oncreate(savedinstancestate);
    //acquire the uri of contentprovider
    getintent().setdata(uri.parse("content://com.example.data_contentprovider.contentproviderclass"));
    uri uri = getintent().getdata();
    //create some data to test
    contentvalues values = new contentvalues();
    values.put("name", "marry");
    values.put("description", "123456");
    getcontentresolver().insert(uri, values); //获取contentresolver对象(在应用程序b中,通过contentresolver获取程序a的contentprovider中的数据。)
    values.put("name", "hello");
    values.put("description", "654321");
    getcontentresolver().insert(uri, values);
    //search db all colum,cursor point to first colum of result
    cursor cursor = managedquery(uri, null, null, null, null);
    cursor.movetofirst();
    //set arraylist,view more field table
    arraylist<map<string,object>> data = new arraylist<map<string,object>>();
    map<string, object> item;
    //from db read data and save to arraylist data container
    for (int i = 0; i < cursor.getcount(); i++) {
      item = new hashmap<string, object>();
      item.put("column00", cursor.getstring(0));
      item.put("column01", cursor.getstring(1));
      item.put("column02", cursor.getstring(2));
      data.add(item);
      cursor.movetonext();
    }
    cursor.close();
    //arraylist container data save to listview
    listview listview = new listview(this);
    simpleadapter adapter = new simpleadapter(this, data, r.layout.activity_content_provider, from, new int[]{r.id.text1,r.id.text2,r.id.text3});
    listview.setadapter(adapter);
    setcontentview(listview);
  }
}

provider应用程序就可以通过该内容提供器检索数据库并向其添加数据了。

contentprovider中重要的几个类:

urimatcher:

要了解urimatcher,首先需要了解android中的uri表示方法,众所周知,uri为通用资源标识符,它代表的是要操作的数据,android中的每一种资源(比如文本,图像,视频等)都可以用uri来表示。android中的uri由以下三部分组成:”content://”(即authory),数据的路径,资源标识id(可选),其中如果存在id,则表示某一个具体的资源,如果不存在id,则表示路径下的整体。因此adduri()函数的3个参数也是对应上面的那3个。urimatcher的匹配过程分为3步:初始化urimatcher;注册需要用的uri;与已经注册的uri进行匹配。

contentresolver :

当使用contentprovider在不同的应用程序中共享数据时,其数据的暴露方式是采取类似数据库中表的方法。而contentresolver 是恰好是采用类似数据库的方法来从contentprovider中存取数据的,它是通过uri来查询contentprovider中提供的数据,查询时,还需知道目的数据库的名称,数据段的数据类型,或者说资源的id。

sqlitequerybuilder:

是一个用来生产sql查询语句的辅助类,可以方便的去访问sqlitedatabase. 在构造sql查询语句时,它同样也需要指定表名,指定列名,指定where条件等。

更多关于android相关内容感兴趣的读者可查看本站专题:《android资源操作技巧汇总》、《android编程开发之sd卡操作方法汇总》、《android文件操作技巧汇总》、《android数据库操作技巧总结》、《android编程之activity操作技巧总结》、《android开发入门与进阶教程》、《android视图view技巧总结》及《android控件用法总结

希望本文所述对大家android程序设计有所帮助。

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

相关文章:

验证码:
移动技术网