在android中经常会用到改变数据库内容后再去使用数据库更新的内容,很多人会重新去query一遍,但是这样的问题就是程序会特别占内存,而且有可能会搂关cursor而导致程序内存未释放等等。其实android内部提供了一种ContentObserver的东西来监听数据库内容的变化。 ContentObserver的构造函数需要一个参数Hanlder,因为ContentObserver内部使用了一个实现Runnable接口的内部类NotificationRunnable,来实现数据库内容的变化。需要使用hanlder去post消息。注册ContentObserver的方法是:getContentResolver().registerContentObserver(uri, notifyForDescendents, observer). 上面3个参数为:uri----Uri类型,是需要监听的数据库的uri. notifyForDescendents---booleantrue的话就会监听所有与此uri相关的uri。false的话则是直接特殊的uri才会监听。一般都设置为true. observer-----ContentObserver就是需要的contentobserver. 初始化一个ContentObserver对象,重载onChange(boolean ),在这个方法里去操作数据库的使用,针对变化后的使用。 写了一个小demo,可以参考下。提示这种监听方式必须是contentprovider才能使用,因为contentprovider有uri.简单的那种sqlite数据库没有uri是使用不了的。 下面demo操作的是在一个activityA里点击button跳转至另外一个activityB,在B中点击button往数据库中加数据,加完后关闭B回到A。A的button的文字自动变化设置到数据库中的字符串。[code] 03 | import android.app.Activity; | 04 | import android.content.Intent; | 05 | import android.database.ContentObserver; | 06 | import android.os.Bundle; | 07 | import android.os.Handler; | 08 | import android.view.View; | 09 | import android.widget.Button; | 11 | public class ListenDataTest extends Activity{ | 12 |
private Button testBtn; | 15 | protected void onCreate(Bundle savedInstanceState) { | 16 | super .onCreate(savedInstanceState); | 17 | setContentView(R.layout.listen_data_test); | 18 | getContentResolver().registerContentObserver(DataChangeProvider.CONTENT_URI, | 21 | testBtn = (Button)findViewById(R.id.test_btn); | 22 | testBtn.setOnClickListener( new View.OnClickListener() { | 24 | public void onClick(View v) { | 25 | Intent in = new Intent(ListenDataTest. this ,DataChangeTest. class ); | 33 | private ContentObserver cob = new ContentObserver( new Handler()) { | 36 | public boolean deliverSelfNotifications() { | 37 | return super .deliverSelfNotifications(); | 41 | public void onChange( boolean selfChange) { | 42 | super .onChange(selfChange); | 43 | testBtn.setText(DataUtils.getChangeName(getApplicationContext())); | 49 | protected void onDestroy() { | 51 | getContentResolver().unregisterContentObserver(cob); | [code] 03 | import android.app.Activity; | 04 | import android.content.ContentValues; | 05 | import android.content.Intent; | 06 | import android.database.ContentObservable; | 07 | import android.database.ContentObserver; | 08 | import android.os.Bundle; | 09 | import android.os.Handler; | 10 | import android.view.View; | 11 | import android.widget.Button; | 13 | public class DataChangeTest extends Activity{ | 14 |
private Button dataBtn; | 15 |
DataSqlite mDataSqlite; | 17 |
protected void onCreate(Bundle savedInstanceState) { | 18 | super .onCreate(savedInstanceState); | 19 | setContentView(R.layout.data_change_test); | 20 | dataBtn = (Button)findViewById(R.id.data_test_btn); | 21 | mDataSqlite = new DataSqlite( this ); | 22 | dataBtn.setOnClickListener( new View.OnClickListener() { | |