ContentProvider
Posted slowdownthenrunfast
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ContentProvider相关的知识,希望对你有一定的参考价值。
DatabaseHelper.java
package com.baxian.s1_contentprovider.db;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
//DatabaseHelper作为一个访问SQLite的助手类,提供两个方面的功能,
//第一,getReadableDatabase(),getWritableDatabase()可以获得SQLiteDatabse对象,通过该对象可以对数据库进行操作
//第二,提供了onCreate()和onUpgrade()两个回调函数,允许我们在创建和升级数据库时,进行自己的操作
public class DatabaseHelper extends SQLiteOpenHelper
private static final int VERSION = 1;
// 在SQLiteOepnHelper的子类当中,必须有该构造函数
public DatabaseHelper(Context context, String name, CursorFactory factory,
int version)
// 必须通过super调用父类当中的构造函数
super(context, name, factory, version);
// TODO Auto-generated constructor stub
public DatabaseHelper(Context context, String name)
this(context, name, VERSION);
public DatabaseHelper(Context context, String name, int version)
this(context, name, null, version);
// 该函数是在第一次创建数据库的时候执行,实际上是在第一次得到SQLiteDatabse对象的时候,才会调用这个方法
@Override
public void onCreate(SQLiteDatabase db)
// TODO Auto-generated method stub
System.out.println("create a Database");
// execSQL函数用于执行SQL语句
// db.execSQL("create table " + FirstProviderMetaData.USERS_TABLE_NAME
// + "(" + FirstProviderMetaData.UserTableMetaData._ID
// + " INTEGER PRIMARY KEY AUTOINCREMENT,"
// + FirstProviderMetaData.UserTableMetaData.USER_NAME
// + " varchar(20));");
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
// TODO Auto-generated method stub
System.out.println("update a Database");
FirstProviderMetadata.java
package com.baxian.s1_contentprovider.cp;
import android.net.Uri;
import android.provider.BaseColumns;
public class FirstProviderMetadata
public static final String AUTHORIY = "com.baxian.s1_contentprovider.cp.FirstContentProviderMatadata";
public static final String DATABASE_NAME = "FirstProvider.db";
public static final int DATABASE_VERSION = 1;
public static final String USERS_TABLE_NAME = "users";
public static final class UserTableMetaData implements BaseColumns
public static final String TABLE_NAME = "users";
// 访问该ContentProvider的URI
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORIY
+ "/users");
// 该ContentProvider所返回的数据类型的定义
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.firstprovider.user";
public static final String CONTENT_TYPE_ITEM = "vnd.android.cursor.item/vnd.firstprovider.user";
// 列名
public static final String USER_NAME = "name";
// 默认的排序方法
public static final String DEFAULT_SORT_ORDER = "_id desc";
FirstContentProvider.java
package com.baxian.s1_contentprovider.cp;
import java.util.HashMap;
import com.baxian.s1_contentprovider.cp.FirstProviderMetadata.UserTableMetaData;
import com.baxian.s1_contentprovider.db.DatabaseHelper;
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.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.TextUtils;
public class FirstContentProvider extends ContentProvider
public static final UriMatcher uriMatcher;
public static final int INCOMING_USER_COLLECTION = 1;
public static final int INCOMING_USER_SINGLE = 2;
private DatabaseHelper dh;
static
uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
uriMatcher.addURI(FirstProviderMetadata.AUTHORIY, "/users",
INCOMING_USER_COLLECTION);
uriMatcher.addURI(FirstProviderMetadata.AUTHORIY, "/users/#",
INCOMING_USER_SINGLE);
public static HashMap<String, String> userProjectionMap;
static
userProjectionMap = new HashMap<String, String>();
userProjectionMap.put(UserTableMetaData._ID, UserTableMetaData._ID);
userProjectionMap.put(UserTableMetaData.USER_NAME,
UserTableMetaData.USER_NAME);
// 是一个回调方法,所以说在ContentProvider创建的时候执行
@Override
public boolean onCreate()
// TODO Auto-generated method stub
// 打开数据库
dh = new DatabaseHelper(getContext(),
FirstProviderMetadata.DATABASE_NAME);
System.out.println("onCreate");
return false;
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder)
// TODO Auto-generated method stub
SQLiteQueryBuilder qb = new SQLiteQueryBuilder();
switch (uriMatcher.match(uri))
case INCOMING_USER_COLLECTION:
qb.setTables(UserTableMetaData.TABLE_NAME);
qb.setProjectionMap(userProjectionMap);
break;
case INCOMING_USER_SINGLE:
qb.setTables(UserTableMetaData.TABLE_NAME);
qb.setProjectionMap(userProjectionMap);
qb.appendWhere(UserTableMetaData._ID + "="
+ uri.getPathSegments().get(1));
break;
String orderby;
if (TextUtils.isEmpty(sortOrder))
orderby = UserTableMetaData.DEFAULT_SORT_ORDER;
else
orderby = sortOrder;
SQLiteDatabase db = dh.getWritableDatabase();
// Cursor c = qb.query(db, projectionIn, selection,
// selectionArgs,groupBy, having, sortOrder);
Cursor c = qb.query(db, projection, selection, selectionArgs, null,
null, orderby);
c.setNotificationUri(getContext().getContentResolver(), uri);
System.out.println("query");
return c;
// 根据传入的URI,返回该URI所表示的数据类型
@Override
public String getType(Uri uri)
// TODO Auto-generated method stub
System.out.println("getType");
switch (uriMatcher.match(uri))
case INCOMING_USER_COLLECTION:
return UserTableMetaData.CONTENT_TYPE;
case INCOMING_USER_SINGLE:
return UserTableMetaData.CONTENT_TYPE_ITEM;
default:
throw new IllegalArgumentException("Unknown URI" + uri);
/**
* 该函数的返回值是一个Uri,这个Uri表示的是刚刚使用这个函数所插入的数据
* content://com.baxian.s1_contentprovider.cp.FirstContentProvider/users/1
*/
@Override
public Uri insert(Uri uri, ContentValues values)
// TODO Auto-generated method stub
System.out.println("insert");
SQLiteDatabase db = dh.getWritableDatabase();
long rowId = db.insert(UserTableMetaData.TABLE_NAME, null, values);
Uri insertUri = null;
if (rowId > 0)
insertUri = ContentUris.withAppendedId(
UserTableMetaData.CONTENT_URI, rowId);
// 通知监听器,数据已经改变
getContext().getContentResolver().notifyChange(insertUri, null);
return insertUri;
return insertUri;
@Override
public int delete(Uri uri, String selection, String[] selectionArgs)
// TODO Auto-generated method stub
System.out.println("delete");
return 0;
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs)
// TODO Auto-generated method stub
System.out.println("update");
return 0;
ContentProviderActivity.java
package com.baxian.s1_contentprovider;
import com.baxian.s1_contentprovider.cp.FirstProviderMetadata;
import android.support.v7.app.ActionBarActivity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ContentProviderActivity extends ActionBarActivity
private Button insert;
private Button query;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
insert = (Button) findViewById(R.id.insert);
query = (Button) findViewById(R.id.query);
InsertListener il = new InsertListener();
insert.setOnClickListener(il);
QureyListener ql = new QureyListener();
query.setOnClickListener(ql);
class InsertListener implements OnClickListener
@Override
public void onClick(View v)
// TODO Auto-generated method stub
System.out.println("click insert button");
ContentValues values = new ContentValues();
values.put(FirstProviderMetadata.UserTableMetaData.USER_NAME,
"zhangsan");
Uri uri = getContentResolver()
.insert(FirstProviderMetadata.UserTableMetaData.CONTENT_URI,
values);
System.out.println("Uri:" + uri);
class QureyListener implements OnClickListener
@Override
public void onClick(View v)
// TODO Auto-generated method stub
System.out.println("click query button");
Cursor c = getContentResolver().query(
FirstProviderMetadata.UserTableMetaData.CONTENT_URI, null,
null, null, null);
while (c.moveToNext())
System.out
.println(c.getString(c
.getColumnIndex(FirstProviderMetadata.UserTableMetaData.USER_NAME)));
@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;
@Override
public boolean onOptionsItemSelected(MenuItem item)
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings)
return true;
return super.onOptionsItemSelected(item);
notice AndroidManifest.xml -->
<provider
android:name=""
android:authorities="" >
</provider>
以上是关于ContentProvider的主要内容,如果未能解决你的问题,请参考以下文章