Question

I have two classes, one is a standard activity, the other a service. I would like the service to update a TextView (via .setText()) of the Activity on certain events that happen within the service.

I've tried to achieve this by programming something like a setter-method inside the Activity-Class, but TextViews don't accept a static-reference, and when I try invoking an instance of the Activity-class instead (via MyActivityClassName aVariable = new MyActivityClassName();), I get a NullPointer Exception, even though the View in questions is visible at the time of the call.

Could anyone tell me what I'm doing wrong :-)? It is probably more of a basic Java question than an Android-one, but since it might have to do with the nature of Android-services, I've still added the android-tag.

Thanks for your help!

Was it helpful?

Solution

I would like the service to update a TextView (via .setText) of the Activity on certain events that happen within the service.

I would strongly recommend greater logical decoupling. Have the Service tell the Activity to update the TextView.

You can do that via a broadcast Intent, or by having the Activity provide a listener object that the Service calls. In either case, be sure the Activity detaches from the service (unregisters the listener or broadcast Intent receiver), lest you cause a memory leak.

And, of course, this only works if the activity is actually running.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top