自定义ContentProvider 实例演示

参考:contentprovider的学习实例总结 http://www.cnblogs.com/chenglong/articles/1892029.html
Android学习十九:ContentProvider初步 http://blog.sina.com.cn/s/blog_5688414b0100xagp.html
android 自定义 Content Provider示例 http://byandby.iteye.com/blog/837466


实例源码下载:http://download.csdn.net/detail/yang_hui1986527/4430639


Profile.java

package com.snowdream.contentprovider;

import android.net.Uri;

public class Profile {
	
	/**
	 * 表格名称
	 */
	public static final String TABLE_NAME = "profile";
	
	/**
	 * 列表一,_ID,自动增加
	 */
	public static final String COLUMN_ID = "_id";
	
	/**
	 * 列表二,名称
	 */
	public static final String COLUMN_NAME = "name";
     
     
    public static final String AUTOHORITY = "com.snowdream.provider";
    public static final int ITEM = 1;
    public static final int ITEM_ID = 2;
     
    public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.snowdream.profile";
    public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.snowdream.profile";
     
    public static final Uri CONTENT_URI = Uri.parse("content://" + AUTOHORITY + "/profile");
}


DBHelper.java

package com.snowdream.contentprovider;

import android.content.Context;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DBHelper extends SQLiteOpenHelper {

	/**
	 * 数据库名称
	 */
	private static final String DATABASE_NAME = "test.db";  
	
	/**
	 * 数据库版本
	 */
	private static final int DATABASE_VERSION = 1;  

	public DBHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
	}

	@Override
	public void onCreate(SQLiteDatabase db)  throws SQLException {
		//创建表格
		db.execSQL("CREATE TABLE IF NOT EXISTS "+ Profile.TABLE_NAME + "("+ Profile.COLUMN_ID +" INTEGER PRIMARY KEY AUTOINCREMENT," + Profile.COLUMN_NAME +" VARCHAR NOT NULL);");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)  throws SQLException {
		//删除并创建表格
		db.execSQL("DROP TABLE IF EXISTS "+ Profile.TABLE_NAME+";");
		onCreate(db);
	}
}


MyProvider.java

package com.snowdream.contentprovider;

import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;

public class MyProvider extends ContentProvider {

	DBHelper mDbHelper = null;
	SQLiteDatabase db = null;

	private static final UriMatcher mMatcher;
	static{
		mMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		mMatcher.addURI(Profile.AUTOHORITY,Profile.TABLE_NAME, Profile.ITEM);
		mMatcher.addURI(Profile.AUTOHORITY, Profile.TABLE_NAME+"/#", Profile.ITEM_ID);
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public String getType(Uri uri) {
		switch (mMatcher.match(uri)) {
		case Profile.ITEM:
			return Profile.CONTENT_TYPE;
		case Profile.ITEM_ID:
			return Profile.CONTENT_ITEM_TYPE;
		default:
			throw new IllegalArgumentException("Unknown URI"+uri);
		}
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		long rowId;
		if(mMatcher.match(uri)!=Profile.ITEM){
			throw new IllegalArgumentException("Unknown URI"+uri);
		}
		rowId = db.insert(Profile.TABLE_NAME,null,values);
		if(rowId>0){
			Uri noteUri=ContentUris.withAppendedId(Profile.CONTENT_URI, rowId);
			getContext().getContentResolver().notifyChange(noteUri, null);
			return noteUri;
		}

		throw new SQLException("Failed to insert row into " + uri);
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		mDbHelper = new DBHelper(getContext());

		db = mDbHelper.getReadableDatabase();

		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		Cursor c = null;
		switch (mMatcher.match(uri)) {
		case Profile.ITEM:
			c =  db.query(Profile.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
			break;
		case Profile.ITEM_ID:
			c = db.query(Profile.TABLE_NAME, projection,Profile.COLUMN_ID + "="+uri.getLastPathSegment(), selectionArgs, null, null, sortOrder);
			break;
		default:
			throw new IllegalArgumentException("Unknown URI"+uri);
		}

		c.setNotificationUri(getContext().getContentResolver(), uri);
		return c;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}

}

MainActivity.java

package com.snowdream.contentprovider;

import com.snowdream.contentprovider.R;

import android.app.ListActivity;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.widget.SimpleCursorAdapter;


public class MainActivity extends ListActivity {
	private SimpleCursorAdapter adapter= null;
	private Cursor mCursor = null;
	private ContentResolver mContentResolver = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		initData();
		initAdapter();
	}

	public void initData(){
		mContentResolver = getContentResolver();

		//填充数据
		for (int i = 0; i < 100; i++) {
			ContentValues values = new ContentValues();
			values.put(Profile.COLUMN_NAME, "张三"+i);
			mContentResolver.insert(Profile.CONTENT_URI, values);
		}
	}


	public void initAdapter(){
		//查询表格,并获得Cursor
		//查询全部数据
		mCursor = mContentResolver.query(Profile.CONTENT_URI, new String[]{Profile.COLUMN_ID,Profile.COLUMN_NAME}, null, null, null);

		//查询部分数据
		//String selection = Profile.COLUMN_ID + " LIKE '%1'";
		//mCursor = mContentResolver.query(Profile.CONTENT_URI, new String[]{Profile.COLUMN_ID,Profile.COLUMN_NAME}, selection, null, null);


		//查询一个数据
		//Uri uri = ContentUris.withAppendedId(Profile.CONTENT_URI, 50);
		//mCursor = mContentResolver.query(uri, new String[]{Profile.COLUMN_ID,Profile.COLUMN_NAME}, null, null, null);

		startManagingCursor(mCursor);

		//设置adapter
		adapter = new SimpleCursorAdapter(this, android.R.layout.simple_list_item_2, mCursor, new String[]{Profile.COLUMN_ID,Profile.COLUMN_NAME}, new int[]{android.R.id.text1,android.R.id.text2});
		setListAdapter(adapter);
	}


	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_main, menu);
		return true;
	}


}

预览效果:


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值