首页 > 技术文章 > ContentProvider示例

qiufeihai 2013-12-10 16:46 原文

http://hi.baidu.com/pekdou/item/b2a070c37552af210831c678

 

首先,我自己是各初学者,网上一些关于ContentProvider的例子也不少,我自己试了很多,但总是有问题,终于今天哥自己写了个出来,自己摸索着写真是太累了。

首先说个查询一条记录的toy demo:

ContentProviderExample(Project name)

     |_src

     |     |_com.motorola.snow.toy

     |          |_ContentProviderExample.java

     |          |_DataProvider.java

     |_res

     |      |_layout

     |      |      |_main.xml

     |      |_values

     |      |_drawable

     |

     |_AndroidManifest.xml

(这是工程的目录,要写这么详细是因为:我看的几个文档都是在讲怎样怎样,没有一个图示。有时候我都不能分辨)

下面一一介绍每个文件需要写写什么东西:

ContentProviderExample.java

package com.motorola.snow.toy;
import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
public class ContentProviderExample extends Activity {
 // public static final String AUTHORITY = "com.motorola.snow";
 public static final Uri CONTENT_URI = Uri
   .parse("content://com.motorola.snow/students");
 private static final String[] PROJECTION = new String[] { "stu_no",
   "stu_name" };
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  TextView tv = (TextView) findViewById(R.id.showOne);
  Cursor c = getContentResolver().query(CONTENT_URI, PROJECTION,
    "stu_no = ?", new String[] { "S1001" }, null);
  c.moveToFirst();
  tv.setText(c.getString(1));
 }
}

DataProvider.java

package com.motorola.snow.toy;
import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.net.Uri;
import android.util.Log;
public class DataProvider extends ContentProvider {
 private static final String DATABASE_NAME = "stu_database";
 private static final int VERSION = 1;
 private static final String TABLE_NAME = "students";
 private DataBaseHelper helper;
 private class DataBaseHelper extends SQLiteOpenHelper {
  public DataBaseHelper(Context context) {
   super(context, DATABASE_NAME, null, VERSION);
  }
  @Override
  public void onCreate(SQLiteDatabase db) {
   // TODO Auto-generated method stub
   db.execSQL("CREATE TABLE students (stu_no TEXT, stu_name TEXT)");
   String sql1 = "insert into students (stu_no, stu_name) values ('S1001', 'Tom')";
   String sql2 = "insert into students (stu_no, stu_name) values ('S1002', 'John')";
   String sql3 = "insert into students (stu_no, stu_name) values ('S1003', 'Jack')";
   try {
    db.execSQL(sql1);
    db.execSQL(sql2);
    db.execSQL(sql3);
   } catch (Exception e) {
    e.printStackTrace();
    Log.println(0, "insert error",
      "Some error occur when create table");
   }
  }
  @Override
  public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
   // TODO Auto-generated method stub
  }
 }
 @Override
 public int delete(Uri arg0, String arg1, String[] arg2) {
  // TODO Auto-generated method stub
  return 0;
 }
 @Override
 public String getType(Uri uri) {
  // TODO Auto-generated method stub
  return null;
 }
 @Override
 public Uri insert(Uri uri, ContentValues values) {
  // TODO Auto-generated method stub
  return null;
 }
 @Override
 public boolean onCreate() {
  helper = new DataBaseHelper(getContext());
  return true;
 }
 @Override
 public Cursor query(Uri uri, String[] projection, String selection,
   String[] selectionArgs, String sortOrder) {
  SQLiteDatabase db = helper.getReadableDatabase();
  Cursor c = db.query("students", projection, selection, selectionArgs, null, null,
    null);
  return c;
 }
 @Override
 public int update(Uri uri, ContentValues values, String selection,
   String[] selectionArgs) {
  // TODO Auto-generated method stub
  return 0;
 }
}
 

main.xml

view plaincopy to clipboardprint?
01.<?xml version="1.0" encoding="utf-8"?>   
02.<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android 
03.    android:orientation="vertical"  
04.    android:layout_width="fill_parent"  
05.    android:layout_height="fill_parent"  
06.    >   
07.<TextView     
08.    android:layout_width="fill_parent"    
09.    android:layout_height="wrap_content"    
10.    android:text="@string/hello"  
11.    />   
12.       
13.<TextView    
14.    android:id="@+id/showOne"  
15.    android:layout_width="fill_parent"    
16.    android:layout_height="wrap_content"       
17.    />   
18.</LinearLayout>  
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
    
<TextView 
 android:id="@+id/showOne"
 android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
 />
</LinearLayout>
 

AndroidManifest.xml

view plaincopy to clipboardprint?
01.<?xml version="1.0" encoding="utf-8"?>   
02.<manifest xmlns:android="http://schemas.android.com/apk/res/android 
03.      package="com.motorola.snow.toy"  
04.      android:versionCode="1"  
05.      android:versionName="1.0">   
06.    <application android:icon="@drawable/icon" android:label="@string/app_name">   
07.        <activity android:name=".ContentProviderExample"  
08.                  android:label="@string/app_name">   
09.            <intent-filter>   
10.                <action android:name="android.intent.action.MAIN" />   
11.                <category android:name="android.intent.category.LAUNCHER" />   
12.            </intent-filter>   
13.        </activity>   
14.    <provider android:name="DataProvider"  
15.              android:authorities="com.motorola.snow" >   
16.    </provider>   
17.    </application>   
18.    <uses-sdk android:minSdkVersion="3" />   
19.</manifest>   
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.motorola.snow.toy"
      android:versionCode="1"
      android:versionName="1.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".ContentProviderExample"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
 <provider android:name="DataProvider"
     android:authorities="com.motorola.snow" >
 </provider>
    </application>
    <uses-sdk android:minSdkVersion="3" />
</manifest> 

其中有几个是一直困扰我的问题,在这个工程中终于得到解决。还是比较高兴的:

1.

在AndroidManifest.xml文件中注册了

    <provider android:name="DataProvider"
              android:authorities="com.motorola.snow" >
    </provider>

  这句话告诉工程,我在这个工程下定义了一个ContentProvider,名字叫DataProvider(这个类大家看到,其实就是ContentProvider的一个自定义的子类) authorities 定义的字符串实际上在ContentProviderExample.java中定义Uri时做的唯一标示符而已,一般我喜欢跟包同名,不过需要注意的是,这个字符串必须全部为小写!!

2.

DataProvider.java实际上是我自己定义的ContentProvider的一个子类,需要重写其继承下来的方法:我只是实现了一个查询功能,但实现了其中的一个功能,其他CRUD的操作应该不难。在这个类里定义了一个内部类:DatabaseHelper extends SQLiteOpenHelper (一开始看的哪个文档也是这样写,可是在eclipse中总是报错,后来才知道必须要重写它的构造方法,这个构造方法的主要作用就是新建数据库,个人理解)实际上在下面DataProvider onCreate 方法中定义了一个DataBaseHelper的实例,在定义的时候他会自行调用DataBaseHelper的 onCreate 方法,创建数据库,因此我为了简单起见,建表并插入了几行数据。这主要要明白这子类中方法的调用顺序,一开始我也很难理解。

3.

说说ContentProviderExample这个类吧:首先定义了

public static final Uri CONTENT_URI = Uri
            .parse("content://com.motorola.snow/students");

其实这是某种固定的写法:这个字符串必须以 content://开始,中间那段要和在AndroidManifest.xml文件中注册的一致,后面一般用的是数据库表名,其实这后面还有一截的是数字,我暂时还不太清楚这最后一段数字的用法,这个具体可以看一下developer.android文档;

下面定义了一个数组:

private static final String[] PROJECTION = new String[] { "stu_no",
            "stu_name" };

这个数组定义的是:在查询中需要查询哪几列,这里我查询的是stu_no和stu_name 2列。

重点说一说下面这段:

Cursor c = getContentResolver().query(CONTENT_URI, PROJECTION,
                "stu_no = ?", new String[] { "S1001" }, null);
        c.moveToFirst();
        tv.setText(c.getString(1));

首先getContentResolver()这个方法返回的是一个ContentProvider的实例,这个方法在所有 Activity中都可以被调用,.query()方法实际上查询的是在DataProvider中重写的query()方法,里面的几个参数分别是Uri,要查询的列,查询条件(where),用来填充查询语句中?号的值,最后是orderBy没有,所以为null,这些参数被传到DataProvider.query()方法中执行。Android会自己拼出一个查询字符串。需要注意的是“stu_no=?”查询条件前面是不需要加where的,android会自行添加。

NOTE:

需要理解的是为什么要定义Uri,我个人的理解:一个比较大的Android工程,可能会用到几个ContentProvider来存储数据,因此在AndroidManifest.xml中注册是需要有个唯一的标识符,不同的URi对应不同的ContentProvider,将Uri作为参数传到query()方法里,就指明了我现在要操作的数据库究竟是哪个

 

本文来自CSDN博客http://blog.csdn.net/tang_jiajia/archive/2010/03/24/5412164.aspx

推荐阅读