使用ContentResolver查询 ContentResolver 共享出来的数据。 使用ContentObserver内容观察者实时监听ContentResolver 共享的数据的变化
代码用例
一、创建一个demo程序 com.example.kangxg.first
1.activity 布局文件
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/bg" android:paddingBottom="16sp" android:paddingLeft="16sp" android:paddingTop="16dp" android:paddingRight="16dp" tools:context=".MailListActivity"> <LinearLayout android:id="@+id/ll_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_above="@+id/ll_phone" android:layout_alignLeft="@+id/ll_btn" android:layout_alignStart="@+id/ll_btn" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18sp" android:text="姓 名:" /> <EditText android:id="@+id/et_name" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="16sp" android:maxLines="1" android:hint="请输入姓名" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/ll_phone" android:layout_marginBottom="10dp" android:layout_above="@+id/ll_btn" android:layout_alignLeft="@+id/ll_name" android:layout_alignStart="@+id/ll_name" android:orientation="horizontal"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:textSize="18dp" android:text="电 话:" /> <EditText android:id="@+id/et_phone" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="16sp" android:maxLines="1" android:hint="请输入手机号" /> </LinearLayout> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/ll_btn" android:orientation="horizontal" android:layout_centerVertical="true"> <Button android:id="@+id/btn_add" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:textSize="18dp" android:background="#B9B9FF" android:layout_marginRight="2dp" android:text="添加" /> <Button android:id="@+id/btn_query" android:layout_width="0dp" android:layout_height="wrap_content" android:textSize="18dp" android:background="#DCB5FF" android:layout_marginRight="2dp" android:layout_weight="1" android:text="查询" /> <Button android:id="@+id/btn_update" android:layout_width="0dp" android:layout_height="wrap_content" android:textSize="18dp" android:background="#E6CAFF" android:layout_marginRight="2dp" android:layout_weight="1" android:text="修改" /> <Button android:id="@+id/btn_delete" android:layout_width="0dp" android:layout_height="wrap_content" android:textSize="18dp" android:background="#ACD6FF" android:layout_weight="1" android:text="删除" /> </LinearLayout> <TextView android:id="@+id/tv_show" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="25dp" android:layout_below="@+id/ll_btn" android:textSize="20sp" android:text="" /> </RelativeLayout>
2.activity实体类
public class MailListActivity extends AppCompatActivity implements View.OnClickListener{ private EditText mEtName; private EditText mEtPhone; private TextView mTvShow; private Button mBtnAdd; private Button mBtnUpdate; private Button mBtnQuery; private Button mBtnDelete; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_mail_list); initView(); } private void initView() { mEtName = (EditText)findViewById(R.id.et_name); mEtPhone = (EditText)findViewById(R.id.et_phone); mTvShow = (TextView)findViewById(R.id.tv_show); mBtnAdd = (Button)findViewById(R.id.btn_add); mBtnQuery = (Button)findViewById(R.id.btn_query); mBtnUpdate = (Button)findViewById(R.id.btn_update); mBtnDelete = (Button)findViewById(R.id.btn_delete); mBtnAdd.setOnClickListener(this); mBtnQuery.setOnClickListener(this); mBtnUpdate.setOnClickListener(this); mBtnDelete.setOnClickListener(this); } private ContentResolver contentResolver; private ContentValues values; private Uri uri; @Override public void onClick(View v) { contentResolver = getContentResolver(); uri = Uri.parse("content://com.example.kangxg.first/userInformation"); values = new ContentValues(); switch (v.getId()) { case R.id.btn_add: values = new ContentValues(); values.put("name",mEtName.getText().toString().trim()); values.put("phone",mEtPhone.getText().toString().trim()); Uri newuri = contentResolver.insert(uri,values); Toast.makeText(this,"信息已经添加",Toast.LENGTH_SHORT).show(); Log.i("数据库应用:","添加"); break; case R.id.btn_query: List<Map<String,String>> data = new ArrayList<Map<String, String>>(); Cursor cursor = contentResolver.query(uri,new String[]{"_id","name","phone"},null,null,null); mTvShow.setText(""); while (cursor.moveToNext()) { Map<String,String> map = new HashMap<String,String>(); map.put("_id",cursor.getString(0)); map.put("name",cursor.getString(1)); map.put("phone",cursor.getString(2)); data.add(map); mTvShow.append("Name: "+ cursor.getString(1)+" :Tel: " + cursor.getString(2)+"\n"); } cursor.close(); Log.i("数据库应用:","查询结果"+data.toString()); break; case R.id.btn_update: String phone ; values.put("phone", phone = mEtPhone.getText().toString().trim()); int updatecount = contentResolver.update(uri,values,"name=?",new String[]{mEtName.getText().toString().trim()}); Toast.makeText(this,"数据更新了"+updatecount+"行",Toast.LENGTH_SHORT).show(); Log.i("数据库应用:","数据更新了"+updatecount+"行"); break; case R.id.btn_delete: int count = contentResolver.delete(uri,"name=?",new String[]{mEtName.getText().toString().trim()}); Toast.makeText(this,"数据成功删除了"+count+"行",Toast.LENGTH_SHORT).show(); Log.i("数据库应用:","数据成功删除了"+count+"行"); break; default: break; } } }
3.创建数据库帮助类
public class UserDBHelper extends SQLiteOpenHelper { private static final String DB_NAME = "user.db"; private static final int DB_VERSION = 2; private static UserDBHelper mHelper = null; private SQLiteDatabase mDB = null; private UserDBHelper(Context context) { super(context,DB_NAME,null,DB_VERSION); } private UserDBHelper(Context context,int version) { super(context,DB_NAME,null,version); } public static UserDBHelper getInstance(Context context,int version) { if (version>0 && mHelper == null) { mHelper = new UserDBHelper(context,version); } else { mHelper = new UserDBHelper(context); } return mHelper; } public SQLiteDatabase openReadLink() { if(mDB == null|| mDB.isOpen() != true) { mDB = mHelper.getReadableDatabase(); } return mDB; } public SQLiteDatabase openWriteLink() { if(mDB == null|| mDB.isOpen() != true) { mDB = mHelper.getWritableDatabase(); } return mDB; } public void closeLink() { if (mDB != null || mDB.isOpen() == true) { mDB.close(); } mDB = null; } public String getDbName() { if (mHelper != null) { return mHelper.getDatabaseName(); } return DB_NAME; } private void createTable(String tablename,SQLiteDatabase db) { if (db != null) { String sql = "create table if not exists userInformation(_id INTEGER PRIMARY KEY AUTOINCREMENT, name VARCHAR(20),phone VARCHAR(20))"; db.execSQL(sql); } } @Override public void onCreate(SQLiteDatabase db) { createTable("usertable",db); } @Override public void onUpgrade(SQLiteDatabase var1, int var2, int var3){ } }
4.创建一个内容提供者ContentProvider
public class UserProvider extends ContentProvider { private static UriMatcher matcher = new UriMatcher((-1)); private static String tablename = "userInformation"; private static final int SUCCESS = 1; private UserDBHelper dbHelper ; static { matcher.addURI("com.example.kangxg.first",tablename,SUCCESS); } @Override public boolean onCreate() { // TODO: Implement this to initialize your content provider on startup. dbHelper = com.example.kangxg.first.tool.UserDBHelper.getInstance(getContext(),2); return false; } public UserProvider() { } @Override public String getType(Uri uri) { // TODO: Implement this to handle requests for the MIME type of the data // at the given URI. return null; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { // TODO: Implement this to handle query requests from clients. int code = matcher.match(uri); if (code == SUCCESS) { SQLiteDatabase db = dbHelper.getWritableDatabase(); return db.query(tablename,projection,selection,selectionArgs,null,null,sortOrder); }else { throw new IllegalArgumentException("路径不正确,停止使用提供数据"); } } @Override public Uri insert(Uri uri, ContentValues values) { // TODO: Implement this to handle requests to insert a new row. int code = matcher.match(uri); if (code == SUCCESS) { SQLiteDatabase db = dbHelper.getReadableDatabase(); long rowid = db.insert(tablename,null,values); if (rowid>0) { Uri insertedUri = ContentUris.withAppendedId(uri,rowid); getContext().getContentResolver().notifyChange(insertedUri,null); return insertedUri; } dbHelper.closeLink(); return uri; } else { throw new IllegalArgumentException("路径不正确,停止插入数据"); } } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // Implement this to handle requests to delete one or more rows. int code = matcher.match(uri); if (code == SUCCESS) { SQLiteDatabase db = dbHelper.getWritableDatabase(); int count = db.delete(tablename,selection,selectionArgs); if (count>0) { getContext().getContentResolver().notifyChange(uri,null); } db.close(); return count; } else { throw new IllegalArgumentException("路径不正确,停止删除数据"); } } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { // TODO: Implement this to handle requests to update one or more rows. int code = matcher.match(uri); if (code == SUCCESS) { SQLiteDatabase db = dbHelper.getReadableDatabase(); int count = db.update(tablename,values,selection,selectionArgs); if (count>0){ getContext().getContentResolver().notifyChange(uri,null); } db.close(); return count; } else { throw new IllegalArgumentException("路径不正确,停止更新数据"); } } }
5创建一个名为MonitorData的程序
public class MainActivity extends AppCompatActivity { private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = (TextView)findViewById(R.id.tv_change); Uri uri = Uri.parse("content://com.example.kangxg.first/userInformation"); getContentResolver().registerContentObserver(uri,true,new MyObserver(new Handler())); } private class MyObserver extends ContentObserver{ public MyObserver(Handler handler) { super(handler); } @Override public void onChange(boolean selfChange) { //Log.i("监测数据变化","有人动了你的程序"); textView.setText("有人动了你的程序"); super.onChange(selfChange); Uri uri = Uri.parse("content://com.example.kangxg.first/userInformation"); ContentResolver resolver = getContentResolver(); Cursor cursor = resolver.query(uri,new String[]{"_id","name","phone"},null,null,null); cursor.moveToFirst(); textView.setText("name:"+cursor.getString(1)+"phone:"+cursor.getString(2)); Log.i("监测数据变化","有人动了你的程序"+"name:"+cursor.getString(1)+"phone:"+cursor.getString(2)); cursor.close(); } } }
二 运行程序
1.首先运行MonitorData程序 再运行first程序
2.在first程序上进行操作
3.在logcat看到日志输出