Android数据库内容变化的监听(附件2)

publicabstractclass CursorAdapter extendsBaseAdapter implementsFilterable,
CursorFilter.CursorFilterClient{
-------------------省略------------------
protectedChangeObservermChangeObserver;
/**
*Thisfieldshouldbemadeprivate,soitishiddenfromtheSDK.
*{@hide}
*/

protectedDataSetObservermDataSetObserver=newMyDataSetObserver();
/**
*Thisfieldshouldbemadeprivate,soitishiddenfromtheSDK.
*{@hide}
*/

-------------------省略------------------
public CursorAdapter(Contextcontext,Cursorc){
init(context,c,true);
}
-------------------省略------------------
protectedvoid init(Contextcontext,Cursorc,booleanautoRequery){
booleancursorPresent=c!=null;
mAutoRequery=autoRequery;
mCursor=c;
mDataValid=cursorPresent;
mContext=context;
mRowIDColumn=cursorPresent?c.getColumnIndexOrThrow("_id"):-1;
mChangeObserver=newChangeObserver();
if(cursorPresent){
c.registerContentObserver(mChangeObserver);
c.registerDataSetObserver(mDataSetObserver);

}
}
-------------------省略------------------
/**
*Changetheunderlyingcursortoanewcursor.Ifthereisanexistingcursoritwillbe
*closed.
*
*@paramcursorthenewcursortobeused
*/

publicvoid changeCursor(Cursorcursor){
if(cursor==mCursor){
return;
}
if(mCursor!=null){
mCursor.unregisterContentObserver(mChangeObserver);
mCursor.unregisterDataSetObserver(mDataSetObserver);
mCursor.close();

}
mCursor=cursor;
if(cursor!=null){
cursor.registerContentObserver(mChangeObserver);
cursor.registerDataSetObserver(mDataSetObserver);

mRowIDColumn=cursor.getColumnIndexOrThrow("_id");
mDataValid=true;
//notifytheobserversaboutthenewcursor
notifyDataSetChanged();
}else{
mRowIDColumn=-1;
mDataValid=false;
//notifytheobserversaboutthelackofadataset
notifyDataSetInvalidated();
}
}
-------------------省略------------------
/**
*Calledwhenthe{@linkContentObserver}onthecursorreceivesachangenotification.
*Thedefaultimplementationprovidestheauto-requerylogic,butmaybeoverriddenby
*subclasses.
*
*@seeContentObserver#onChange(boolean)
*/

protectedvoid onContentChanged(){
if(mAutoRequery&&mCursor!=null&&!mCursor.isClosed()){
if(Config.LOGV)Log.v("Cursor","Autorequerying"+mCursor+"duetoupdate");
mDataValid=mCursor.requery();
}
}

privateclass ChangeObserver extendsContentObserver{
public
ChangeObserver (){
super(newHandler());
}

@Override
publicboolean deliverSelfNotifications (){
returntrue;
}

@Override
publicvoid onChange (booleanselfChange){
onContentChanged();
}
}

privateclass MyDataSetObserver extends DataSetObserver{
@Override
publicvoid onChanged() {
mDataValid=true;
notifyDataSetChanged();
}
@Override
publicvoid onInvalidated() {
mDataValid=false;
notifyDataSetInvalidated();
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值