I am trying to create an application that contains Content Observers in a remote service but kept getting the error:
"Can’t create handler inside thread that has not called Looper prepare"
I have done much reading on the Android Developers site as well as many Google searches I am still not fully understanding the problem. What I've taken from it so far is that the Content Observer needs a thread to run on (for the Handler). After adding:
Looper.myLooper().prepare();
mObserver = new Observer(new Handler());
a Looper call immediately before creating a new Content Observer makes the application work correctly. However I would like a better understanding of why this is - nothing I have found online has help me grasp why thus far. Also, is adding the Looper line of code the correct and efficient thing to do? And is there any cleanup I need to do with this to prevent memory leaks later down the road?
The simpler the explanation the better. Still in my first month of Android Development and making good progress - StackOverflow has been a tremendous help! Thanks.
UPDATE
After playing around and doing more reading I think have a better grasp on how to make this work and how to clean it up but still missing one small part.
From what I've gathered I can call Looper.prepare() as a static method. I can then create my Content Observer using the new Handler(). When I want to stop this Content Observer I can get the thread of the object with mLooper = Looper.myLooper.getThread() and then I can run a mLooper.quit(). However must I and when would I and why would I call mLooper.loop()?
UPDATE 2
Okay so here the problem I am addressing. The application is in house and is a little complicated to explain but here is my best shot:
We have a remote service running that receives and sends network data. Our message types are defined in the data so we can direct them to the correct database on the phone. There is a Jar interface file for other APK's to import to connect to the service running. These APK's can register to receive broadcasts when a new message they are interested in is received. To do this a content observer is registered with the content uri the APK uses thus when new data is added to the database a the content observer will send out a broadcast to alert the correct APK. The APK can then handle this however it wishes.
So would it be okay to use null as the parameter of a new Content Observer or would it be better to use new Handler() to create a thread for this observer.
I have tried creating a thread but so far it is not working, I think its because I have not started the Looper.loop (this freezes my service). Any advice would be greatly appreciated! Thanks in advance.