Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why and when to unregister content observers in android

I am developing an android application and first time working with content observers. So I read a lot of tutorials and got the concept that why it is provided and how to use.

Now I have read these lines on a blog that

Dont forget to unregister content observers

So, I am not able to understand if I want to register a ContentObserver then what may be the situation in which I have to unregister it.

If the purpose of the observers get fulfilled then its ok, we can unregister it. But I have to observe till user uninstalls the application, then why I will be going to unregister the observer.

Here is the url of that blog

http://www.grokkingandroid.com/use-contentobserver-to-listen-to-changes/

like image 927
Nikhil Agrawal Avatar asked Apr 04 '13 11:04

Nikhil Agrawal


People also ask

Do we need to unregister observer android?

You register your observer in the onResume() lifecycle method and you unregister it in the onPause() method. once you unregister it one of these method's . it will not observe any value and ll not give any memory leak also. It depends on you where you want to unregister it.

What is content observer?

ContentObserver is an abstract class with no abstract methods. Its two onChange() methods are implemented without any logic. And since these are called whenever a change occurs, you have to override them.


1 Answers

Imagine you have an application that has let's say a friend list screen created using a FriendListActivity. Now to create UI for this activity you read data from the DB and create your UI.

Now imagine that you also have a service that runs in background and syncs this database with a remote database using web services.

Now whenever the service updates the friend list in the DB you want to also update your UI accordingly. So, to achieve this you would register content observer in your FriendListActivity at the time of Activity launch for Friends URI (assuming that know the concept of URI), so that whenever the friend list in database changes you would also update friends list in your FriendListActivity. Now if the user moved out of your activity or closes the app then you don't need to update your UI (so you don't need to get event for DB changes), so you would unregister the content observer.

Now the next time user comes to this screen, you would again fetch the latest data and register with the DB for content changes...

So the content observer is normally a relation between an activity and database (or specific URI). SO you would register it when the Activity gets launched and un-register it when the activity goes out of the view..

Hope this helps...

like image 151
Praful Bhatnagar Avatar answered Oct 10 '22 07:10

Praful Bhatnagar