玩转Android Provider

参考:http://blog.csdn.net/yan8024/article/details/6444368



package com.HelloWorld;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.content.ContentProvider;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Environment;

public class MyProvider extends ContentProvider {

	
	private final static String DB_DIR = "lp";
	private final static String DB_NAME = "contacts.db";
	private final static String TABLE_NAME = "PRMContacts";
	private Context mContext;
	private SQLiteDatabase db ;
	private  static  final  String AUTHORITY = "com.helloword.myprovider" ;
	private  static  UriMatcher uriMatcher;  
	private  static  final  int  ONE = 1 ;  
	private  static  final  int  MORE = 2 ;  
	static   
    {  
        //  添加访问ContentProvider的Uri   
        uriMatcher = new  UriMatcher(UriMatcher.NO_MATCH);  
        uriMatcher.addURI(AUTHORITY, "one" , ONE);  
        uriMatcher.addURI(AUTHORITY, "more/*" , MORE);  
    }  
	
	@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 Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public boolean onCreate() {
		mContext = getContext();
		db = openDatabase();
		return true;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) {
		Cursor cursor = null;
		System.out.println("query");
		switch(uriMatcher.match(uri)){
			case ONE:
				cursor = db.query(TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder);
				break;
			case MORE:
				String word = uri.getPathSegments().get(1);
				cursor = db.rawQuery("select * from "+TABLE_NAME+" where displayname like ?", new String[]{word+"%"});
				break;
			default:
				throw new IllegalArgumentException("无效参数");
		}
		return cursor;
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		return 0;
	}
	
	 private SQLiteDatabase openDatabase()
	    {
        	if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
        		FileOutputStream fos = null;
        		InputStream is = null;
        		try
    	        {
	        		String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/"+DB_DIR;
	        		
	        		// 获得dictionary.db文件的绝对路径
		            String databaseFilename = path + "/" + DB_NAME;
		            File dir = new File(path);
		            
		            if(!dir.exists()){
		            	dir.mkdir();
		            }
		            
		            File db = new File(databaseFilename);
		            if(!db.exists()){
		            	fos = new FileOutputStream(db);
		            	is = mContext.getResources().openRawResource(R.raw.contacts);
		            	
		            	byte[] buffer = new byte[1024];
		            	int length = 0;
		            	while((length = is.read(buffer))!=-1){
		            		fos.write(buffer, 0, length);
		            	}
		            }
		            
		            SQLiteDatabase database = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
		            return database;
		        }
		        catch (Exception e){
		        	
		        }finally{
		        	if(fos!=null){
		        		try {
							fos.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		        	}
		        	if(is!=null){
		        		try {
							is.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
		        	}
		        }
        	}
	            
	        return null;
	    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android ProviderAndroid 系统提供的一种数据存储方式,它提供了可供其他应用程序访问的公共数据集合。使用 Provider 可以实现数据共享,使得不同的应用程序可以访问和修改同一数据集合,从而实现数据的共享和协作。 在 Android 中,Provider 通常用于存储和共享应用程序的数据,比如联系人、短信、音乐、视频等。开发者可以通过 ContentResolver 类来访问 Provider 中的数据。 使用 Provider 的步骤如下: 1. 创建数据表结构:定义 Provider 中所需的数据表结构; 2. 创建 ContentProvider 子类:实现 Provider 中的 CRUD(增删改查)操作; 3. 在 AndroidManifest.xml 文件中注册 ContentProvider:声明 Provider 的信息; 4. 在应用程序中使用 ContentResolver 访问 Provider 中的数据。 接下来是一个简单的示例,演示如何创建一个 Provider 并向其中插入一条数据: 1. 首先,定义 Provider 中需要使用的数据表结构,比如: ``` public class MyProvider extends SQLiteOpenHelper { // 声明数据库名和版本号 public static final String DB_NAME = "my_provider.db"; public static final int DB_VERSION = 1; // 声明数据表名和字段名 public static final String TABLE_NAME = "users"; public static final String COLUMN_ID = "id"; public static final String COLUMN_NAME = "name"; // 构造函数 public MyProvider(Context context) { super(context, DB_NAME, null, DB_VERSION); } // 创建数据表 @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE " + TABLE_NAME + " (" + COLUMN_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + COLUMN_NAME + " TEXT NOT NULL" + ");"); } // 升级数据表 @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + TABLE_NAME); onCreate(db); } } ``` 2. 然后,创建一个 ContentProvider 子类,继承自 ContentProvider,并实现 CRUD 操作,比如: ``` public class MyContentProvider extends ContentProvider { // 声明 Provider 的唯一标识 public static final String AUTHORITY = "com.example.myprovider"; // 声明 UriMatcher 对象 private static final UriMatcher sUriMatcher = new UriMatcher(UriMatcher.NO_MATCH); private static final int USERS = 1; private static final int USER_ID = 2; // 声明 MyProvider 对象 private MyProvider mProvider; // 初始化 UriMatcher static { sUriMatcher.addURI(AUTHORITY, MyProvider.TABLE_NAME, USERS); sUriMatcher.addURI(AUTHORITY, MyProvider.TABLE_NAME + "/#", USER_ID); } // 获取 ContentProvider 所使用的数据源 @Override public boolean onCreate() { mProvider = new MyProvider(getContext()); return true; } // 查询数据 @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { SQLiteDatabase db = mProvider.getReadableDatabase(); Cursor cursor = null; switch (sUriMatcher.match(uri)) { case USERS: cursor = db.query(MyProvider.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); break; case USER_ID: String id = uri.getLastPathSegment(); cursor = db.query(MyProvider.TABLE_NAME, projection, MyProvider.COLUMN_ID + "=?", new String[]{id}, null, null, sortOrder); break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } cursor.setNotificationUri(getContext().getContentResolver(), uri); return cursor; } // 插入数据 @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = mProvider.getWritableDatabase(); long id = db.insert(MyProvider.TABLE_NAME, null, values); if (id > 0) { Uri itemUri = ContentUris.withAppendedId(uri, id); getContext().getContentResolver().notifyChange(uri, null); return itemUri; } else { throw new SQLException("Failed to insert row into " + uri); } } // 更新数据 @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { SQLiteDatabase db = mProvider.getWritableDatabase(); int count = 0; switch (sUriMatcher.match(uri)) { case USERS: count = db.update(MyProvider.TABLE_NAME, values, selection, selectionArgs); break; case USER_ID: String id = uri.getLastPathSegment(); count = db.update(MyProvider.TABLE_NAME, values, MyProvider.COLUMN_ID + "=?", new String[]{id}); break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } // 删除数据 @Override public int delete(Uri uri, String selection, String[] selectionArgs) { SQLiteDatabase db = mProvider.getWritableDatabase(); int count = 0; switch (sUriMatcher.match(uri)) { case USERS: count = db.delete(MyProvider.TABLE_NAME, selection, selectionArgs); break; case USER_ID: String id = uri.getLastPathSegment(); count = db.delete(MyProvider.TABLE_NAME, MyProvider.COLUMN_ID + "=?", new String[]{id}); break; default: throw new IllegalArgumentException("Unknown URI: " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } // 获取 MIME 类型 @Override public String getType(Uri uri) { switch (sUriMatcher.match(uri)) { case USERS: return "vnd.android.cursor.dir/" + AUTHORITY + "." + MyProvider.TABLE_NAME; case USER_ID: return "vnd.android.cursor.item/" + AUTHORITY + "." + MyProvider.TABLE_NAME; default: throw new IllegalArgumentException("Unknown URI: " + uri); } } } ``` 3. 在 AndroidManifest.xml 文件中注册 ContentProvider,比如: ``` <provider android:name=".MyContentProvider" android:authorities="com.example.myprovider" android:exported="false" /> ``` 4. 在应用程序中使用 ContentResolver 访问 Provider 中的数据,比如: ``` // 查询用户列表 Cursor cursor = getContentResolver().query(Uri.parse("content://com.example.myprovider/users"), null, null, null, null); while (cursor.moveToNext()) { int id = cursor.getInt(cursor.getColumnIndex(MyProvider.COLUMN_ID)); String name = cursor.getString(cursor.getColumnIndex(MyProvider.COLUMN_NAME)); Log.d(TAG, "id=" + id + ", name=" + name); } // 插入一条用户数据 ContentValues values = new ContentValues(); values.put(MyProvider.COLUMN_NAME, "Alice"); Uri uri = getContentResolver().insert(Uri.parse("content://com.example.myprovider/users"), values); Log.d(TAG, "insert uri: " + uri); // 更新用户数据 values.put(MyProvider.COLUMN_NAME, "Bob"); int count = getContentResolver().update(Uri.parse("content://com.example.myprovider/users/1"), values, null, null); Log.d(TAG, "update count: " + count); // 删除用户数据 count = getContentResolver().delete(Uri.parse("content://com.example.myprovider/users/1"), null, null); Log.d(TAG, "delete count: " + count); ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值