Jack Wachira
Jack Wachira

Reputation: 192

how to findViewById in a Service Class in android

I have a class that extends service and the service basically fetches data from the cloud and lists ot in a listview..am getting an error when i try to use "findviewById" method to get the listview because the class doesn't extend Activity.does anyone know how i should go about it.

Upvotes: 0

Views: 2597

Answers (2)

android_dev
android_dev

Reputation: 1477

Hi There in my opinion better to use the AsncTask in that you have to write the backend downloading data part in doinBackground method and setting the data to the list view in onPostexcute.

Better have a look into the asynctask

http://developer.android.com/reference/android/os/AsyncTask.html

mean while try to bind a service and make communication from service to activity for this have a look into how to bind a service.

for binding a service

http://developer.android.com/guide/components/bound-services.html

Upvotes: 0

CommonsWare
CommonsWare

Reputation: 1007474

Your service cannot modify the UI directly. In fact, there may not be a UI at all, as the user may have pressed BACK and destroyed the activity while the network I/O is going on.

Instead, you need to send a message from the service to the activity to let the activity know, if it exists, that there is new data. For this, you can use:

  • LocalBroadcastManager from the Android Support package, or
  • a third-party message bus implementation, like Square's Otto, or
  • a Messenger tied to a Handler
  • etc.

Upvotes: 1

Related Questions