本文主要是介绍Android开发入门之监听ContentProvider中数据的变化,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
新建Aapp工程,向主页面添加一个按钮
public void insert(View v) {Uri uri = Uri.parse("content://cn.leigo.providers.personprovider/person");ContentResolver resolver = this.getContentResolver();ContentValues values = new ContentValues();values.put("name", "A-App");values.put("phone", "18800000000");values.put("amount", 12000);resolver.insert(uri, values);}
该按钮向person插入一条数据
在db工程的insert方法中,
@Overridepublic Uri insert(Uri uri, ContentValues values) {SQLiteDatabase db = dbOpenHelper.getWritableDatabase();switch (MATCHER.match(uri)) {case PERSONS:long rowid = db.insert("person", "name", values); // 主键值// content://cn.leigo.providers.personprovider/person/10// Uri insertUri =// Uri.parse("content://cn.leigo.providers.personprovider/person/"+// rowid);Uri insertUri = ContentUris.withAppendedId(uri, rowid);//发出数据变化通知this.getContext().getContentResolver().notifyChange(uri, null);return insertUri;default:throw new IllegalArgumentException("this is Unknow Uri:" + uri);}}
新建Bapp工程监听Aapp向Person表中添加数据时发生的变化
package cn.leigo.bapp;import android.app.Activity;
import android.database.ContentObserver;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;public class MainActivity extends Activity {private static final String TAG = "MainActivity";@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);Uri uri = Uri.parse("content://cn.leigo.providers.personprovider/person");this.getContentResolver().registerContentObserver(uri, true,new Observer(new Handler()));}private class Observer extends ContentObserver {public Observer(Handler handler) {super(handler);}@Overridepublic void onChange(boolean selfChange) {Uri uri = Uri.parse("content://cn.leigo.providers.personprovider/person");Cursor cursor = getApplicationContext().getContentResolver().query(uri, null, null, null,"personid desc limit 1");if (cursor.moveToFirst()) {String name = cursor.getString(cursor.getColumnIndex("name"));Log.i(TAG, name);}}}}
这篇关于Android开发入门之监听ContentProvider中数据的变化的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!