项目中突然想用Content Provider实现跨应用操作数据的功能,虽然后来没有利用Content Provider来实现。但还是写了个简单demo程序,熟悉一下Content Provider的开发。这篇文章只是简单记录下,下一篇文章具体解释需要注意的问题
两个项目,一个继承Content Provider将数据库的CRUD操作显露给其他应用,另一个项目,则是进行CRUD操作。很简单的功能。
-----------------------------------------------------------
项目1:
首先创建 DatabaseHelper
private static String DATABASE_NAME = "db_name";
public static String TABLE_NAME = "db_table_name";
public static String COL_ID = "_id";
public static String COL_TXT = "txt";
public DatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, 1);
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("create table if not exists " + TABLE_NAME + "(" + COL_ID
+ " integer primary key autoincrement, " + COL_TXT + " text )");
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// TODO Auto-generated method stub
db.execSQL("drop table if exists " + TABLE_NAME);
onCreate(db);
}
然后实现 Content Provider功能
private static final String TAG = "TestContentProvider";
private DatabaseHelper dbHelper;
// public constants for client development
public static final String AUTHORITY = "info.zhegui.contentprovider.provider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + DatabaseHelper.TABLE_NAME);
// helper constants for use with the UriMatcher
private static final int LENTITEM_LIST = 1;
private static final int LENTITEM_ID = 2;
private static final UriMatcher URI_MATCHER;
/**
* Column and content type definitions for the LentItemsProvider.
*/
public static interface LentItems extends BaseColumns {
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
+ "/vnd.info.zhegui.provider." + DatabaseHelper.TABLE_NAME;
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
+ "/vnd.info.zhegui.provider." + DatabaseHelper.TABLE_NAME;
}
static {
URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH);
URI_MATCHER.addURI(AUTHORITY, DatabaseHelper.TABLE_NAME, LENTITEM_LIST);
URI_MATCHER.addURI(AUTHORITY, DatabaseHelper.TABLE_NAME + "/#",
LENTITEM_ID);
}
@Override
public int delete(Uri uri, String selection, String[] selectionArgs) {
int rowNum = dbHelper.getWritableDatabase().delete(
DatabaseHelper.TABLE_NAME, selection, selectionArgs);
return rowNum;
}
@Override
public String getType(Uri uri) {
switch (URI_MATCHER.match(uri)) {
case LENTITEM_LIST:
return LentItems.CONTENT_TYPE;
case LENTITEM_ID:
return LentItems.CONTENT_ITEM_TYPE;
default:
throw new IllegalArgumentException("Unsupported URI: " + uri);
}
}
@Override
public Uri insert(Uri uri, ContentValues values) {
long rowId = dbHelper.getWritableDatabase().insert(
DatabaseHelper.TABLE_NAME, null, values);
return Uri.parse(CONTENT_URI + "/" + rowId);
}
@Override
public boolean onCreate() {
dbHelper = new DatabaseHelper(getContext());
return true;
}
@Override
public Cursor query(Uri uri, String[] projection, String selection,
String[] selectionArgs, String sortOrder) {
if (URI_MATCHER.match(uri) != LENTITEM_LIST) {
throw new IllegalArgumentException(
"Unsupported URI for insertion: " + uri);
}
return dbHelper.getReadableDatabase().query(DatabaseHelper.TABLE_NAME,
projection, selection, selectionArgs, null, null, null);
}
@Override
public int update(Uri uri, ContentValues values, String selection,
String[] selectionArgs) {
int rowNum = dbHelper.getWritableDatabase().updateWithOnConflict(
DatabaseHelper.TABLE_NAME, values, selection, selectionArgs,
SQLiteDatabase.CONFLICT_FAIL);
return rowNum;
}
接下来在manifest中声明
<provider
android:name="TestContentProvider"
android:authorities="info.zhegui.contentprovider.provider"
android:exported="true" />
ok,项目就完成了。就是这么简单!
-------------------------------------------------------------------------------------------
项目2:
只是简单调用CRUD操作,直接上代码
public static String TABLE_NAME = "db_table_name";
public static final String AUTHORITY = "info.zhegui.contentprovider.provider";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY
+ "/" + TABLE_NAME);
public static String COL_ID = "_id";
public static String COL_TXT = "txt";
public static interface LentItems extends BaseColumns {
public static final String CONTENT_TYPE = ContentResolver.CURSOR_DIR_BASE_TYPE
+ "/vnd.info.zhegui.provider." + TABLE_NAME;
public static final String CONTENT_ITEM_TYPE = ContentResolver.CURSOR_ITEM_BASE_TYPE
+ "/vnd.info.zhegui.provider." + TABLE_NAME;
}
private EditText etIccid;
private ListView listView;
private CustomAdapter mAdapter;
private Handler handler;
private List<Item> listData = new ArrayList<Item>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
handler = new Handler(this);
etIccid = (EditText) findViewById(R.id.et);
listView = (ListView) findViewById(R.id.listview);
mAdapter = new CustomAdapter();
((Button) findViewById(R.id.btn_add))
.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final String txt = etIccid.getEditableText().toString();
if (!TextUtils.isEmpty(txt)) {
new Thread() {
public void run() {
ContentValues values = new ContentValues();
values.put(COL_TXT, txt);
Uri uri = getContentResolver().insert(
CONTENT_URI, values);
if (uri != null) {
getData();
}
}
}.start();
}
etIccid.setText("");
}
});
listView.setAdapter(mAdapter);
getData();
}
private synchronized void getData() {
new Thread() {
public void run() {
listData.clear();
Cursor cursor = getContentResolver().query(CONTENT_URI, null,
null, null, null);
Log.i(TAG, "line 100 cursor:" + cursor);
if (cursor != null) {
while (cursor.moveToNext()) {
long id = cursor.getLong(cursor.getColumnIndex(COL_ID));
String str = cursor.getString(cursor
.getColumnIndex(COL_TXT));
listData.add(new Item(id, str));
}
}
handler.sendEmptyMessage(0);
}
}.start();
}
@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;
}
public static class ViewHolder {
EditText et;
Button btnUpdate;
Button btnDelete;
}
public class Item {
long id;
public Item(long id, String str) {
this.id = id;
this.txt = str;
}
public long getId() {
return id;
}
public String getTxt() {
return txt;
}
String txt;
}
public class CustomAdapter extends BaseAdapter {
public CustomAdapter() {
}
@Override
public int getCount() {
return listData.size();
}
@Override
public Object getItem(int position) {
return listData.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(final int position, View convertView,
ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
holder = new ViewHolder();
convertView = LayoutInflater.from(MainActivity.this).inflate(
R.layout.list_item, parent, false);
holder.et = (EditText) convertView.findViewById(R.id.et_item);
holder.btnUpdate = (Button) convertView
.findViewById(R.id.btn_update);
holder.btnDelete = (Button) convertView
.findViewById(R.id.btn_delete);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.et.setText(listData.get(position).getTxt());
holder.et.setTag("et_" + position);
holder.btnDelete.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// listData.remove(position);
// mAdapter.notifyDataSetChanged();
int rowId = getContentResolver()
.delete(CONTENT_URI,
COL_ID + " =? ",
new String[] { listData.get(position)
.getId() + "" });
if (rowId != 0) {
getData();
}
}
});
holder.btnUpdate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String et = ((EditText) listView.findViewWithTag("et_"
+ position)).getText().toString();
if (!TextUtils.isEmpty(et)) {
// listData.set(position, et);
// mAdapter.notifyDataSetChanged();
ContentValues values = new ContentValues();
values.put(COL_TXT, et);
int rowId = getContentResolver().update(
CONTENT_URI,
values,
COL_ID + " =? ",
new String[] { listData.get(position).getId()
+ "" });
if (rowId != 0) {
getData();
}
}
}
});
return convertView;
}
}
@Override
public boolean handleMessage(Message msg) {
mAdapter.notifyDataSetChanged();
return false;
}
。
附2个项目源码