0

In my main activity i am using a view pager which shows two fragments. One for recent messages and another online contacts. In my contact fragment i am binding activity to a service named ContactService. ContactService has an interface FragmentConnected which has a public method like this:

interface FragmentConnected {

        public void onFragmentConnected(ArrayList<Contact> clist);

}

In my ContactFragment i am implementing this interface like this

public void onFragmentConnected(ArrayList clist) {

                      onlineContactAdapter.changeList(clist);
           }

Here onlineContactAdapter is my adpter for ContactFragment has a method changeList for updating list of online users.

In my service ContactService in onHandleIntent i am getting list of online users from server and i am calling method contactFragment.onFragmentConnected as i have instance of ContactFragment in contactFragment when it binds to service. EveryThing is running fine until i call this method onFragmentConnected from service . When i am calling this method from service it is giving me this error:- android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.

abc
  • 29
  • 4
  • Your service is calling your callback from a different thread than the main thread... it seems. So your activity service callback is getting called on a background thread causing that issue. I would recommend that you call your service callback from the main thread. – Jona May 27 '16 at 18:46
  • But i have to update online contact list from service so how can i can call this method from service as UI MainThread? Is there any method? – abc May 27 '16 at 18:50
  • I'm not sure exactly how you implemented your ContactService. But your data pull from a server is happening on a background thread. After you get that data you post to send your updates via the main thread. There many ways you can do that. Most easy using Handler. http://stackoverflow.com/questions/11123621/running-code-in-main-thread-from-another-thread – Jona May 27 '16 at 18:54
  • Thanks for your help. I just made Handler object and post a thread into post method and then i called my ui method from this thread and it worked. – abc May 27 '16 at 19:26
  • Great! I'm just adding my response as an answer I guess... :P – Jona May 29 '16 at 19:20

1 Answers1

0

I'm not sure exactly how you implemented your ContactService. But your data pull from a server is happening on a background thread. After you get that data you need to post to send your updates via the main thread. There many ways you can do that.

Most easy using Handler. Running code in main thread from another thread

Community
  • 1
  • 1
Jona
  • 13,325
  • 15
  • 86
  • 129