today I was learning about Intents and binding an activity to service, I found it quite easy and great way to transfer data from the service to the activity. I wanted to test out an activity that would start a service, this service would call on a webpage to get some data. I binded the activity to the service so that the activity could call on the service method and then toast the results. In the service method I call on a webpage and return the data. When I tested it I was getting a null pointer exception, im pretty sure I am not doing it the right way , does anyone have any suggestions how to implement this properly.
-
Without seeing some part of the code it's impossible to tell. – Brian Dupuis Feb 03 '12 at 21:30
-
The next thing it would be helpful to know is where in there the crash occurs, instead of having us play needle in a haystack :). – Brian Dupuis Feb 03 '12 at 22:04
-
Im getting a null pointer exception in the activity class, where the for loop is, this must mean that the vector being returned has nothing in it thus the service is never adding anything to the vector – Grady-lad Feb 03 '12 at 22:10
2 Answers
You're dealing with some fairly solid thread synchronization issues here. You would be far better served registering some kind of listener paradigm such that you register your Activity as a listener to the data that your Service is producing. As it currently stands, there's no synchronization between your Service and Activity at all, resulting in the Activity trying to fetch the results from the Service before they're ready. There are a ton of resources out there discussing the listener pattern or Observer pattern.
I should note, I have no idea whether your Service is actually pulling things down correctly. I'm just looking at your communication between the two.

- 8,136
- 3
- 25
- 29
-
I know there is a lot of threading issues here, I was messing around with intents 1st then was going to look into handlers but it looks like I should get around the threading issue 1st – Grady-lad Feb 03 '12 at 22:25
When returning results from service , its better to implement ResultReceiver interface in you activity and pass receiver object to the service via putExtra. In your service fetch the receiver object and call receiver.send() function to send anything in Bundle. [I have tested this pattern in IntentService at least].
Edit:check out this post for complete implementation.

- 1
- 1

- 8,034
- 6
- 41
- 43