android 数据共享 ContentProvider
2013-03-05 17:36 waddell 阅读(195) 评论(0) 编辑 收藏 举报1、定义我共享的SQLite的数据信息
package com.example.phonedemo.contentprovider; import android.net.Uri; import android.provider.BaseColumns; public class MyDatabaseInfo { public static final String Auth = "com.example.phonedemo.contentprovider"; public static final String DBNAME = "cp"; public static final int DBVERSION = 1; public static class MyTabInfo implements BaseColumns{ public static final String TABNAME = "member"; public static final Uri CONTENT_URI = Uri.parse("content://" + Auth + "/" + TABNAME); public static final String CONTENT_LIST = "vnd.android.cursor.dir/vnd.phonedemocontentprovider.member"; public static final String CONTENT_ITEM = "vnd.android.cursor.item/vnd.phonedemocontentprovider.member"; public static final String NAME = "name"; public static final String AGE = "age"; public static final String EMAIL = "email"; } }
2、写一个类继承SQLiteOpenHelper,完成一些数据库的初始化的操作。
package com.example.phonedemo.contentprovider; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; public class MySQLiteOpenHepler extends SQLiteOpenHelper { public MySQLiteOpenHepler(Context context) { super(context, MyDatabaseInfo.DBNAME, null, MyDatabaseInfo.DBVERSION); // TODO Auto-generated constructor stub } @Override public void onCreate(SQLiteDatabase db) { String sql = "CREATE TABLE " + MyDatabaseInfo.MyTabInfo.TABNAME + " (" + MyDatabaseInfo.MyTabInfo._ID + " INTEGER PRIMARY KEY," + MyDatabaseInfo.MyTabInfo.NAME + " VARCHAR(50) NOT NULL," + MyDatabaseInfo.MyTabInfo.AGE + " INTEGER NOT NULL," + MyDatabaseInfo.MyTabInfo.EMAIL + " VARCHAR(50) NOT NULL" + ")"; db.execSQL(sql); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { String sql = "DROP TABLE IF EXISTS " + MyDatabaseInfo.MyTabInfo.TABNAME; db.execSQL(sql); this.onCreate(db); } }
3、首先写一个类继承 ContentProvider
package com.example.phonedemo.contentprovider; 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 MyContentProvider extends ContentProvider { private static UriMatcher uriMatcher = null; private MySQLiteOpenHepler helper = null; private static final int GET_MEMBER_LIST = 1; private static final int GET_MEMBER_ITEM = 2; static { uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(MyDatabaseInfo.Auth, MyDatabaseInfo.MyTabInfo.TABNAME, GET_MEMBER_LIST); uriMatcher.addURI(MyDatabaseInfo.Auth, MyDatabaseInfo.MyTabInfo.TABNAME + "/#", GET_MEMBER_ITEM); } @Override public int delete(Uri uri, String where, String[] whereArgs) { SQLiteDatabase db = this.helper.getWritableDatabase(); int count = 0; switch (uriMatcher.match(uri)) { case GET_MEMBER_LIST: count = db.delete(MyDatabaseInfo.MyTabInfo.TABNAME, null, null); break; case GET_MEMBER_ITEM: count = db.delete(MyDatabaseInfo.MyTabInfo.TABNAME, where, whereArgs); break; default: db.close(); throw new UnsupportedOperationException("Not Support " + uri); } db.close(); return count; } @Override public String getType(Uri arg0) { // TODO Auto-generated method stub return null; } @Override public Uri insert(Uri uri, ContentValues values) { SQLiteDatabase db = this.helper.getWritableDatabase(); long id = 0; switch (uriMatcher.match(uri)) { case GET_MEMBER_LIST: id = db.insert(MyDatabaseInfo.MyTabInfo.TABNAME, null, values); return ContentUris.withAppendedId(uri, id); case GET_MEMBER_ITEM: break; default: throw new UnsupportedOperationException("Not Support Uri: " + uri); } db.close(); return null; } @Override public boolean onCreate() { // TODO Auto-generated method stub this.helper = new MySQLiteOpenHepler(super.getContext()); return false; } @Override public Cursor query(Uri uri, String[] arg1, String arg2, String[] arg3, String arg4) { SQLiteDatabase db = this.helper.getWritableDatabase(); Cursor cursor = null; switch (uriMatcher.match(uri)) { case GET_MEMBER_LIST: System.out.println("** get member list"); cursor = db.query(MyDatabaseInfo.MyTabInfo.TABNAME, null, null, null, null, null, null); System.out.println("contentProvider cursor.getCount(): " + cursor.getCount()); break; case GET_MEMBER_ITEM: System.out.println("** get member item"); break; default: throw new UnsupportedOperationException("Not Support Uri: " + uri); } //db.close(); return cursor; } @Override public int update(Uri uri, ContentValues values, String whereSelection, String[] whereArgs) { SQLiteDatabase db = this.helper.getWritableDatabase(); int result = 0; switch (uriMatcher.match(uri)) { case GET_MEMBER_LIST: result = db.update(MyDatabaseInfo.MyTabInfo.TABNAME, values, null, null); break; case GET_MEMBER_ITEM: result = db.update(MyDatabaseInfo.MyTabInfo.TABNAME, values, whereSelection, whereArgs); break; default: db.close(); throw new UnsupportedOperationException("不支持该操作!"); } db.close(); return result; } }
4、写一个测试类继承与Activity,测试,我们的contentprovider 能否正常运行
package com.example.phonedemo; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.ContentResolver; import android.content.ContentUris; 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.ArrayAdapter; import android.widget.Button; import android.widget.FrameLayout.LayoutParams; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.Toast; import com.example.phonedemo.contentprovider.MyDatabaseInfo; public class MyCPActivity extends Activity { private LayoutParams wrap_h = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT); private LayoutParams wrap_v = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); private LayoutParams match = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT); private LinearLayout scream = null; private LinearLayout layout = null; private Button insertBut = null; private Button updateBut = null; private Button deleteBut = null; private Button queryBut = null; private ListView list = null; private ArrayAdapter<String> adapter = null; private List<String> contentList = new ArrayList<String>(); public long insert(String name, int age, String email) { ContentResolver contentResolver = null; contentResolver = super.getContentResolver(); ContentValues values = new ContentValues(); values.put(MyDatabaseInfo.MyTabInfo.NAME, name); values.put(MyDatabaseInfo.MyTabInfo.AGE, age); values.put(MyDatabaseInfo.MyTabInfo.EMAIL, email); Uri uri = contentResolver.insert(MyDatabaseInfo.MyTabInfo.CONTENT_URI, values); return ContentUris.parseId(uri); } public long update(int id, String name, int age, String email) { int r = 0; ContentResolver result = super.getContentResolver(); ContentValues values = new ContentValues(); values.put(MyDatabaseInfo.MyTabInfo.NAME, name); values.put(MyDatabaseInfo.MyTabInfo.AGE, age); values.put(MyDatabaseInfo.MyTabInfo.EMAIL, email); if ("".equals(id) || 0 == id) { // 更新全部 r = result.update(MyDatabaseInfo.MyTabInfo.CONTENT_URI, values, null, null); } else { r = result.update(ContentUris.withAppendedId( MyDatabaseInfo.MyTabInfo.CONTENT_URI, id), values, " _id = ?", new String[] { String.valueOf(id) }); } return r; } public int delelte(int id) { ContentResolver resolver = super.getContentResolver(); int count = 0; if ("".equals(id) || 0 == id) { // 删除全部 count = resolver.delete(MyDatabaseInfo.MyTabInfo.CONTENT_URI, null, null); } else { // 根据传入的ID删除数据 count = resolver.delete(ContentUris.withAppendedId( MyDatabaseInfo.MyTabInfo.CONTENT_URI, id), "_id=?", new String[] { String.valueOf(id) }); } return count; }; public List<String> query() { List<String> all = new ArrayList<String>(); ContentResolver resolver = super.getContentResolver(); Cursor cursor = resolver.query(MyDatabaseInfo.MyTabInfo.CONTENT_URI, null, null, null, null); for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) { all.add("id: " + cursor.getInt(0) + ", name: " + cursor.getString(1) + ", age: " + cursor.getInt(2)); } System.out.println("** all.size(): " + all.size()); return all; } @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); this.scream = new LinearLayout(this); this.scream.setOrientation(LinearLayout.VERTICAL); this.layout = new LinearLayout(this); this.layout.setOrientation(LinearLayout.HORIZONTAL); this.insertBut = new Button(this); this.insertBut.setText("增加"); this.insertBut.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub int id = (int) MyCPActivity.this.insert("qinxijuan", 30, "niitqin@163.com"); Toast.makeText(MyCPActivity.this, "增加成功。id = " + id, Toast.LENGTH_LONG).show(); } }); this.layout.addView(this.insertBut, wrap_h); this.updateBut = new Button(this); this.updateBut.setText("更新"); this.updateBut.setOnClickListener(new OnClickListener() { @Override public void onClick(View arg0) { // TODO Auto-generated method stub int id = (int) MyCPActivity.this.update(0, "qinxijuan", 18, "rigoberto@126.com"); Toast.makeText(MyCPActivity.this, "更新成功。id = " + id, Toast.LENGTH_LONG).show(); } }); this.layout.addView(this.updateBut, wrap_h); this.deleteBut = new Button(this); this.deleteBut.setText("删除"); this.deleteBut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub int count = (int) MyCPActivity.this.delelte(0); Toast.makeText(MyCPActivity.this, "删除" + count + "条记录。", Toast.LENGTH_LONG).show(); } }); this.layout.addView(this.deleteBut, wrap_h); this.queryBut = new Button(this); this.queryBut.setText("查询"); this.queryBut.setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { // TODO Auto-generated method stub MyCPActivity.this.contentList = MyCPActivity.this.query(); MyCPActivity.this.adapter = new ArrayAdapter<String>(MyCPActivity.this, android.R.layout.simple_list_item_1, MyCPActivity.this.contentList); MyCPActivity.this.list.setAdapter(adapter); } }); this.layout.addView(this.queryBut, wrap_h); this.scream.addView(this.layout, wrap_v); this.list = new ListView(this); this.adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, this.contentList); this.list.setAdapter(adapter); this.scream.addView(this.list, this.wrap_v); super.addContentView(scream, match); } }
5、需要在自己的应用的AndroidMainiFest.xml文件中开放自己的ContnetProvider,并设置read/write权限,这样其他应用才能访问该应用的数据。
<provider android:name=".contentprovider.MyContentProvider" android:authorities="com.example.phonedemo.contentprovider" android:readPermission="com.example.phonedemo.contentprovider.READ_PERMISSON" android:writePermission="com.example.phonedemo.contentprovider.WRITE_PERMISSON" />