Aleena
Aleena

Reputation: 273

How to implement ContentObserver?

I have a ContentProvider , using it I am populating my ListView. I need to click one of the menu-item. It updates my data sets but i need to reflect the changes in the ListView. I read about ContentObserver but i am still confused how to implement it actually. Here is my Code.

MYContentObserver

@SuppressLint("NewApi")
    public class MyObserver extends ContentObserver {        
        public MyObserver(Handler handler) {
            super(handler);            
        }
        @Override
        public void onChange(boolean selfChange) {
            List<Contact> newData;
            if(CONTACT_TYPE == VOIP_CONTACTS){
                newData = ContactsManager.getVoipContacts(getActivity());
            }else{
                newData = ContactsManager.getAllContacts(getActivity());
            }
            customAdapter.contacts().clear();
            customAdapter.contacts().addAll(newData);
            customAdapter.notifyDataSetChanged();
        }
    }

And I am regsitering it in my onCreate like :

getActivity().getContentResolver().registerContentObserver(MyContentProvider.CONTENT_URI, true, myObserver);

Now What??? Is that is? or I need to call some method etc??

**Edite**

My update method in my content provider is :

       @Override
   public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) {
      int count = 0;
      switch (uriMatcher.match(uri)){
      case CONTACT:
         count = db.update(CONTACTS_TABLE_NAME, values, 
                 selection, selectionArgs);
         break;
      case CONTACT_ID:
         count = db.update(CONTACTS_TABLE_NAME, values, _ID + 
                 " = " + uri.getPathSegments().get(1) + 
                 (!TextUtils.isEmpty(selection) ? " AND (" +
                 selection + ')' : ""), selectionArgs);
         break;
      default: 
         throw new IllegalArgumentException("Unknown URI " + uri );
      }
      getContext().getContentResolver().notifyChange(uri, null);
      return count;
   }

And in my onOptionItemSelected, on click of one of the item, m updating like :

getActivity().getContentResolver().update(ContactsContentProvider.CONTENT_URI, values, where, null);

Upvotes: 3

Views: 3856

Answers (1)

zozelfelfo
zozelfelfo

Reputation: 3776

It seems ok to me, every time your URI CONTENT_URI gets updated (insert, delete or modify) your ContentObserver should be triggered, if your onChange() method is not getting called, make sure that you are pointing to the right URI in your ContentProvider.

One thing you should add is the unregister of your content observer, in your onPause() method you should do the following:

getContentResolver().unregisterContentObserver(myObserver);

Hope it helps!

Upvotes: 3

Related Questions