关于android中自定义contentprovider的使用

  在android开发中,有时需要在一个应用中调用操作系统中的另一个应用,而这个操作需要用到contentprovider,今天学习自定义的contentprovider,在android中contentprovider实际上是操作sqlite数据库来增删查改数据的,所以我们需要先写一个继承自SqliteOpenhelper的类,来创建数据库

      MysqliteOpenhelper类

public class MySqliteOpenhelper extends SQLiteOpenHelper {
	private String dbName = "people.db";
	public MySqliteOpenhelper(Context context, String name,
			CursorFactory factory, int version) {
		super(context, name, null,1);
		// TODO Auto-generated constructor stub
	}

	@Override
	public void onCreate(SQLiteDatabase db) {
		// TODO Auto-generated method stub
		//创建userinfo表的sql语句
		String sql = "create table userinfo(id int auto_increate,name varchar(30),age int,phone varchar(50))";
		db.execSQL(sql);//创建表
	}

	@Override
	public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
		// TODO Auto-generated method stub
	}

}

    接下来创建需要操作的UserInfo实体类

public class UserInfo {
	private int id;
	private String name;
	private String phone;
	private int age;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
	public UserInfo(int id, String name, String phone, int age) {
		super();
		this.id = id;
		this.name = name;
		this.phone = phone;
		this.age = age;
	}
	public UserInfo(String name, String phone, int age) {
		super();
		this.name = name;
		this.phone = phone;
		this.age = age;
	}
	@Override
	public String toString() {
		return "UserInfo [id=" + id + ", name=" + name + ", phone=" + phone
				+ ", age=" + age + "]";
	}
	<span style="color:#ff0000;">
}</span>
 创建需要向其他应用提供数据操作的contentprovider,MyContentProvider类


public class MyContentProvider extends ContentProvider {

	private  UriMatcher uriMatcher;//声明需要封装uri的urimatcher
	private  MySqliteOpenhelper helper;//声明创建数据库的helper
	private static final int USERINFO = 1;
	private static final int USERINFOS = 2;
	 

	@Override
	public boolean onCreate() {
		// TODO Auto-generated method stub
		uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);
		//添加uri
		uriMatcher.addURI("com.test.self.provider","userinfo/#",USERINFO);//#是一个通配符
		uriMatcher.addURI("com.test.self.provider","userinfos",USERINFOS);//整张表
		helper = new MySqliteOpenhelper(getContext());
		return true;
	}

	
	@Override
	public int delete(Uri uri, String selection, String[] selectionArgs) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = helper.getWritableDatabase();
		int deleteNumber;
		switch (uriMatcher.match(uri)) {
		case USERINFOS://删除全部数据
			deleteNumber = db.delete("userinfo",selection,selectionArgs);
			return deleteNumber;
		case USERINFO:
			long id = ContentUris.parseId(uri);//解析得到需要删除的行的id
			String where = "id="+id;
			if (selection != null && !"".equals(selection)) {//如果有其他条件
				where = selection +" and "+where;
			}
			deleteNumber = db.delete("userinfo",where,selectionArgs);
			return deleteNumber;
		default:
			throw new IllegalArgumentException("unknow uri:"+uri);
		}
	}

	@Override
	public String getType(Uri arg0) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Uri insert(Uri uri, ContentValues values) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = helper.getWritableDatabase();
		long insertId;
		switch (uriMatcher.match(uri)) {
		case USERINFOS:
			insertId = db.insert("userinfo",null,values);//null表示每一列都插入
			return ContentUris.withAppendedId(uri, insertId);//更新uri
		default:
			throw new IllegalArgumentException("unknow uri:"+uri);
		}
		
	}

	@Override
	public Cursor query(Uri uri, String[] projection, String where, String[] whereArgs,
			String sortOrder) {
		// TODO Auto-generated method stub
		Cursor cursor;
		SQLiteDatabase db = helper.getWritableDatabase();//得到创建好的db数据库
		switch (uriMatcher.match(uri)) {
		case USERINFO://content://com.test.self.provider/userinfo/4,,,,对id为4的userinfo查询操作
			long id = ContentUris.parseId(uri);//解析得到id,即id=4
			String wheres = "id="+id;
			if (null != where && !"".equals(where)) {
				wheres = where +" and "+wheres;
			}
			cursor = db.query("userinfo",projection,wheres,whereArgs,null,null,sortOrder);
			return cursor;
		case USERINFOS://查询所有
			cursor = db.query("userinfo",projection,where,whereArgs,null,null,sortOrder);
			return cursor;
		default:
			throw new IllegalArgumentException("unknow uri:"+uri);
		}
	}

	@Override
	public int update(Uri uri, ContentValues values, String where, String[] whereArgs) {
		// TODO Auto-generated method stub
		SQLiteDatabase db = helper.getWritableDatabase();
		int updateNumber;
		switch (uriMatcher.match(uri)) {
		case USERINFOS://更改所有数据
			updateNumber = db.update("userinfo",values,where, whereArgs);
			return updateNumber;
		case USERINFO://更改一条数据
			long id = ContentUris.parseId(uri);
			String whereClause = "id="+id;
			if (where != null && !"".equals(where)) {
				whereClause = where + " and "+whereClause;
			}
			
			updateNumber= db.update("userinfo", values, whereClause, whereArgs);
			return updateNumber;
		default:
			throw new IllegalArgumentException("unknow uri:"+uri);
		}
	}

}

需要注意这里需要在清单文件里配置该provider

 <provider
            android:name="com.example.mycontentprovider.MyContentProvider"
            android:authorities="com.test.self.provider"
            android:exported="true"
            >
新建一个应用,调用contentprovider操作数据

public class MainActivity extends Activity {
	private Button addone;
	private Button addall;
	private Button deleteone;
	private Button deleteall;
	private Button queryone;
	private Button queryall;
	private Button updateone;
	private Button updateall;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		addone = (Button) findViewById(R.id.addone);
		addall = (Button) findViewById(R.id.addAll);
		deleteone = (Button) findViewById(R.id.deleteone);
		deleteall = (Button) findViewById(R.id.deleteall);
		queryone = (Button) findViewById(R.id.queryone);
		queryall = (Button) findViewById(R.id.queryall);
		updateone = (Button) findViewById(R.id.updateone);
		updateall = (Button) findViewById(R.id.updateall);
		
		addone.setOnClickListener(new MyClickListener());
		addall.setOnClickListener(new MyClickListener());
		deleteone.setOnClickListener(new MyClickListener());
		deleteall.setOnClickListener(new MyClickListener());
		queryone.setOnClickListener(new MyClickListener());
		queryall.setOnClickListener(new MyClickListener());
		updateone.setOnClickListener(new MyClickListener());
		updateall.setOnClickListener(new MyClickListener());
	}

	public class MyClickListener implements OnClickListener {
		Uri uri = null;
		Cursor cursor;
		@Override
		public void onClick(View view) {
			// TODO Auto-generated method stub
			switch (view.getId()) {
			case R.id.addone:
				uri = Uri.parse("content://com.test.self.provider/userinfos");
				ContentValues values = new ContentValues();
				values.put("name","wangwu");
				values.put("phone","264546");
				values.put("age", 20);
				getContentResolver().insert(uri, values);
				break;
			case R.id.addAll:
				uri = Uri.parse("conent://com.test.self.provider/userinfos");
				for (int i = 0; i < 5; i++) {
					ContentValues values2 = new ContentValues();
					values2.put("name","zhangsan");
					values2.put("phone","264546");
					values2.put("age", 20);
					getContentResolver().insert(uri, values2);
				}
			case R.id.deleteone:
				uri = Uri.parse("conent://com.test.self.provider/userinfo/3");//删除第三条数据
				getContentResolver().delete(uri, null, null);
			case R.id.deleteall:
				uri = uri.parse("conent://com.test.self.provider/userinfos");
				getContentResolver().delete(uri, null, null);
			case R.id.queryone:
				uri = Uri.parse("conent://com.test.self.provider/userinfo/6");//查询第六条数据
				cursor = getContentResolver().query(uri, null, null, null, null);
				if (cursor.moveToNext()) {
					int id = cursor.getInt(cursor.getColumnIndex("id"));
					String name = cursor.getString(cursor.getColumnIndex("name"));
					int age = cursor.getInt(cursor.getColumnIndex("age"));
					String phone = cursor.getString(cursor.getColumnIndex("phone"));
					System.out.println("id---"+id+"--name--"+name+"--age--"+age+"--phone--"+phone);
				}
				cursor.close();
			case R.id.queryall:
				uri = Uri.parse("conent://com.test.self.provider/userinfos");
				cursor = getContentResolver().query(uri, null, null, null, null);
				while (cursor.moveToNext()) {
					int id = cursor.getInt(cursor.getColumnIndex("id"));
					String name = cursor.getString(cursor.getColumnIndex("name"));
					int age = cursor.getInt(cursor.getColumnIndex("age"));
					String phone = cursor.getString(cursor.getColumnIndex("phone"));
					System.out.println("id---"+id+"--name--"+name+"--age--"+age+"--phone--"+phone);
				}
				cursor.close();
			case R.id.updateone:
				uri = Uri.parse("conent://com.test.self.provider/userinfo/6");
				ContentValues values3 = new ContentValues();
				values3.put("age",50);
				getContentResolver().update(uri, values3, null, null);
			case R.id.updateall:
				uri = Uri.parse("conent://com.test.self.provider/userinfos");
				ContentValues values4 = new ContentValues();
				values4.put("name","lisi");
				getContentResolver().update(uri, values4, null,null);
			default:
				break;
			}
		}
		
	}
}
该mainactivity的布局代码如下:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:id="@+id/addone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="addone" />

    <Button
        android:id="@+id/addAll"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="addall" />

    <Button
        android:id="@+id/deleteone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="deleteone" />

    <Button
        android:id="@+id/deleteall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="deleteall" />

    <Button
        android:id="@+id/queryone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="queryone" />

    <Button
        android:id="@+id/queryall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="queryall" />

    <Button
        android:id="@+id/updateone"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="updateone" />
      <Button
        android:id="@+id/updateall"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="updateall" />

</LinearLayout>





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值