Content Provider数据存储实例

一、Content Provider基本概念

1、ContentProvider为存储和获取数据提供了统一的接口。ContentProvide对数据进行封装,不用关心数据存储的细节。使用表的形式来组织数据。

2、使用ContentProvider可以在不同的应用程序之间共享数据。 
3、Android为常见的一些数据提供了默认的ContentProvider(包括音频、视频、图片和通讯录等)。   
ContentProvider所提供的函数:

query(),insert(),update(),delete(),getType(),onCreate()等。


 二、URI(统一资源标识符)的使用方法
为系统的每一个资源给其一个名字,比方说通话记录。
1、每一个ContentProvider都拥有一个公共的URI,这个URI用于表示这个ContentProvider所提供的数据。 
2、Android所提供的ContentProvider都存放在android.provider包中。 将其分为A,B,C,D 4个部分:
Content Provider数据存储实例_第1张图片
A:标准前缀,用来说明一个Content Provider控制这些数据,无法改变的;"content://"
B:URI 的标识,它定义了是哪个Content Provider提供这些数据。对于第三方应用程序,为了保证URI标识的唯一性,它必须是一个完整的、小写的 类名。这个标识在 元素的 authorities属性中说明:一般是定义该ContentProvider的包.类的名称;"content://hx.android.text.myprovider"
C:路径,不知道是不是路径,通俗的讲就是你要操作的数据库中表的名字,或者你也可以自己定义,记得在使用的时候保持一致就ok了;"content://hx.android.text.myprovider/tablename"

D:如果URI中包含表示需要获取的记录的ID;则就返回该id对应的数据,如果没有ID,就表示返回全部; "content://hx.android.text.myprovider/tablename/#" #表示数据id


Content Provider增删改查实例(通过listview显示操作过的数据)

1,创建person库,person表

package com.example.contentproviderdemo2;

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

public class DBOpenHelper extends SQLiteOpenHelper {
    
	private static final String DATABASE_NAME = "person.db"; //数据库名称
	private static final int DATABASE_VERSION = 1;//数据库版本
	
	public DBOpenHelper(Context context) {
		super(context, DATABASE_NAME, null, DATABASE_VERSION);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		  
		db.execSQL("CREATE TABLE person (_id integer primary key autoincrement, name varchar(20), age varchar(10))");
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
		// TODO Auto-generated method stub
		db.execSQL("DROP TABLE IF EXISTS person");
		onCreate(db);
	}

}

2,自定义Content Provider类,增删改查的方法

package com.example.contentproviderdemo2;

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.net.Uri;

public class PersonProvider extends ContentProvider {
	private DBOpenHelper dbOpenHelper;
	private static final UriMatcher MATCHER = new UriMatcher(
			UriMatcher.NO_MATCH);
	private static final int PERSONS = 1;
	private static final int PERSON = 2;
	static {
		MATCHER.addURI("cn.com.karl.personProvider", "person", PERSONS);
		MATCHER.addURI("cn.com.karl.personProvider", "person/#", PERSON);
	}

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		this.dbOpenHelper = new DBOpenHelper(this.getContext());
		return false;
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String selection,
			String[] selectionArgs, String sortOrder) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = dbOpenHelper.getReadableDatabase();
		switch (MATCHER.match(uri)) {
		case PERSONS://查询所有的
			return db.query("person", projection, selection, selectionArgs,
					null, null, sortOrder);

		case PERSON://查询某一id的人的信息
			long id = ContentUris.parseId(uri);
			String where = "_id=" + id;
			if (selection != null && !"".equals(selection)) {
				where = selection + " and " + where;
			}
			return db.query("person", projection, where, selectionArgs, null,
					null, sortOrder);

		default:
			throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
		}
	}
    
	//返回数据的MIME类型。
	@Override
	public String getType(Uri uri) {
		// TODO Auto-generated method stub
		switch (MATCHER.match(uri)) {
		case PERSONS:
			return "vnd.android.cursor.dir/person";

		case PERSON:
			return "vnd.android.cursor.item/person";

		default:
			throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
		}
	}

	// 插入person表中的所有记录 /person
	// 插入person表中指定id的记录 /person/10
	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		switch (MATCHER.match(uri)) {
		case PERSONS:
			// 特别说一下第二个参数是当name字段为空时,将自动插入一个NULL。
			long rowid = db.insert("person", "name", values);
			Uri insertUri = ContentUris.withAppendedId(uri, rowid);// 得到代表新增记录的Uri
			this.getContext().getContentResolver().notifyChange(uri, null);
			return insertUri;

		default:
			throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
		}
	}

	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		int count = 0;
		switch (MATCHER.match(uri)) {
		case PERSONS:
			count = db.delete("person", selection, selectionArgs);
			return count;

		case PERSON:
			long id = ContentUris.parseId(uri);
			String where = "_id=" + id;
			if (selection != null && !"".equals(selection)) {
				where = selection + " and " + where;
			}
			count = db.delete("person", where, selectionArgs);
			return count;

		default:
			throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
		}
	}

	@Override
	public int update(Uri uri, ContentValues values, String selection,
			String[] selectionArgs) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = dbOpenHelper.getWritableDatabase();
		int count = 0;
		switch (MATCHER.match(uri)) {
		case PERSONS:
			count = db.update("person", values, selection, selectionArgs);
			return count;
		case PERSON:
			long id = ContentUris.parseId(uri);
			String where = "_id=" + id;
			if (selection != null && !"".equals(selection)) {
				where = selection + " and " + where;
			}
			count = db.update("person", values, where, selectionArgs);
			return count;
		default:
			throw new IllegalArgumentException("Unkwon Uri:" + uri.toString());
		}
	}

}
 

3,activity

package com.example.contentproviderdemo2;


import android.app.Activity;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.Toast;

public class ResolverDemoActivity extends Activity {  
    /** Called when the activity is first created. */  
    private SimpleCursorAdapter adapter;  
    private ListView listView; 
    private Button button_insert;
    private Button button_query;
    private Button button_query_one;
    private EditText edittext_query;
    private Button button_update_one;
    private EditText edittext_update;
    private Button button_update;
    private Button button_delete;
    private Button button_delete_one;
    private EditText edittext_delete;
    
    
    
    @SuppressWarnings("deprecation")
	@Override  
    public void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.main);  
          
        listView=(ListView) this.findViewById(R.id.listView);  
        ContentResolver contentResolver = getContentResolver();  
        Uri selectUri = Uri.parse("content://cn.com.karl.personProvider/person");  
        Cursor cursor=contentResolver.query(selectUri, null, null, null, null);  
		adapter = new SimpleCursorAdapter(this, R.layout.item, cursor,  
                    new String[]{"_id", "name", "age"}, new int[]{R.id.id, R.id.name, R.id.age});  
            listView.setAdapter(adapter);  
            listView.setOnItemClickListener(new OnItemClickListener() {  
                @Override  
                public void onItemClick(AdapterView parent, View view, int position, long id) {  
                    ListView lView = (ListView)parent;  
                    Cursor data = (Cursor)lView.getItemAtPosition(position);  
                    int _id = data.getInt(data.getColumnIndex("_id"));  
                    Toast.makeText(ResolverDemoActivity.this, _id+"", 1).show();  
                }  
            });  
              
            button_insert = (Button) this.findViewById(R.id.insertbutton);  
            button_insert.setOnClickListener(new OnClickListener() {            
                @Override  
                public void onClick(View v) {  
                    ContentResolver contentResolver = getContentResolver();  
                    Uri insertUri = Uri.parse("content://cn.com.karl.personProvider/person");  
                    ContentValues values = new ContentValues();  
                    values.put("name", "wangkuifeng");  
                    values.put("age", 23);  
                    Uri uri = contentResolver.insert(insertUri, values);  
                    Toast.makeText(ResolverDemoActivity.this, "添加完成", 1).show();  
                }  
            }); 
            
            button_query = (Button)this.findViewById(R.id.querybutton);
            button_query.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					    ContentResolver contentResolver = getContentResolver();  
	                    Uri selectUri = Uri.parse("content://cn.com.karl.personProvider/person");  
	                    
	                    Cursor cursor=contentResolver.query(selectUri, null, null, null, null);
	                    SimpleCursorAdapter adapter= new SimpleCursorAdapter(ResolverDemoActivity.this, R.layout.item, cursor,  
	                            new String[]{"_id", "name", "age"}, new int[]{R.id.id, R.id.name, R.id.age});  
	                    listView.setAdapter(adapter);
	                    
	                    Toast.makeText(ResolverDemoActivity.this, "查询完成", 1).show(); 
				}
			});
            button_query_one = (Button)this.findViewById(R.id.queryonebutton);
            edittext_query = (EditText)this.findViewById(R.id.queryone_et);
            button_query_one.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					String num = edittext_query.getText().toString();
					ContentResolver contentResolver = getContentResolver();  
	                Uri selectUri = Uri.parse("content://cn.com.karl.personProvider/person"+"/"+num);
	                Cursor cursor=contentResolver.query(selectUri, null, null, null, null);
                    SimpleCursorAdapter adapter = new SimpleCursorAdapter(ResolverDemoActivity.this, R.layout.item, cursor,  
                            new String[]{"_id", "name", "age"}, new int[]{R.id.id, R.id.name, R.id.age});  
                    listView.setAdapter(adapter);
                    
                    Toast.makeText(ResolverDemoActivity.this, "查询完成", 1).show(); 
				}
			});
            edittext_update = (EditText)this.findViewById(R.id.update_et);
            button_update_one = (Button)this.findViewById(R.id.updateonebutton);
            button_update_one.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					String num = edittext_update.getText().toString();
					ContentResolver contentResolver = getContentResolver();  
	                Uri updateUri = Uri.parse("content://cn.com.karl.personProvider/person"+"/"+num);
	                ContentValues values = new ContentValues();  
                    values.put("name", "superjunjin");  
                    values.put("age", 26);  
	                int count = contentResolver.update(updateUri, values, null, null);
                   
                    
                    Toast.makeText(ResolverDemoActivity.this, "更新完成", 1).show(); 
				}
			});
            
            button_update = (Button)this.findViewById(R.id.updatebutton);
            button_update.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					ContentResolver contentResolver = getContentResolver(); 
					Uri updateUri = Uri.parse("content://cn.com.karl.personProvider/person");
	                ContentValues values = new ContentValues();  
                    values.put("name", "superjunjin");  
                    values.put("age", 26);  
	                int count = contentResolver.update(updateUri, values, null, null);
                   
                    Toast.makeText(ResolverDemoActivity.this, "更新完成", 1).show(); 
				}
			});
            
            button_delete = (Button)this.findViewById(R.id.deletebutton);
            button_delete.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					ContentResolver contentResolver = getContentResolver(); 
					Uri deleteUri = Uri.parse("content://cn.com.karl.personProvider/person");
					contentResolver.delete(deleteUri, null, null);
					
					Toast.makeText(ResolverDemoActivity.this, "删除完成", 1).show(); 
				}
			});
            
            edittext_delete = (EditText)this.findViewById(R.id.delete_et);
            button_delete_one = (Button)this.findViewById(R.id.deleteonebutton);
            button_delete_one.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					// TODO Auto-generated method stub
					String num = edittext_delete.getText().toString();
					ContentResolver contentResolver = getContentResolver();  
	                Uri deleteUri = Uri.parse("content://cn.com.karl.personProvider/person"+"/"+num);
	               
	                contentResolver.delete(deleteUri, null, null);
                   
                    
                    Toast.makeText(ResolverDemoActivity.this, "删除完成", 1).show();
				}
			});
            
    }  
}  

参考  http://blog.csdn.net/wangkuifeng0118/article/details/7028953

http://blog.csdn.net/huangbiao86/article/details/6679823


实例下载 http://download.csdn.net/detail/superjunjin/7245993

你可能感兴趣的:(android,其他)