Question

The application that I'm working on has an activity with three fragments. Each fragment needs to show some data that is received from an IntentService.

Fragment 1 - the icon, the name and the description Fragment 2 - a list of articles Fragment 3 - a list of items

public class Activity extends SherlockFragmentActivity implements Actionbar.Tablistener
{

    public void onCreate(..) {

        ....
        performSearch();
        setupTabs(); // 3 tabs are setup, their clicks and swipes init'ed
        ...

    }

    @Override
    public void onResume() { 

      IntentFilter intentFilter = new IntentFilter(SearchRequestReceiver.ACTION);
      intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
      searchRequestReceiver = new SearchRequestReceiver(this);
      registerReceiver(searchRequestReceiver, intentFilter);

    }

    @Override 
    public void onPause() {

      unregisterReceivers();

    }
    ...

    public void performSearch() {

        Intent intent = new Intent(this, SearchRequest.class);
        intent.putExtra("searchTerm", this.searchTerm); // declared and initialised earlier
        startService(intent);
    }

    ...
}

What is the best way for me to push this data from my receiver to my fragments or am I approaching this the wrong way? I didn't use AsyncTasks because I wanted to decouple my services from the context or was that the wrong decision?

Was it helpful?

Solution

An EventBus is one of the neatest solutions in this situation. EventBus and Otto are both very easy to use.

An example using Otto...

Your IntentService

new Handler(Looper.getMainLooper()).post(new Runnable() {
   bus.post(new DataLoadCompleteEvent());
});

Note the necessity to post the event on Android's main thread with Otto. In this case, a DataLoadCompleteEvent could contain whatever you wanted.

Your Fragment

@Subscribe public void onLoad(DataLoadCompleteEvent event) {
    //Do stuff with event
}

Just make sure your Fragments register on the bus in their onResume(), and unregister in their onPause().

OTHER TIPS

I've managed to get it working by having the different receivers within my fragments but it seems like an awful lot of repetition.

public class FragmentName extends SherlockFragment 
{

   private SearchRequestReceiver searchRequestReceiver;

   ..

   public class ServiceRequestReceiver extends BroadcastReceiver
   {

        @Override
        public void onReceive(Context context, Intent intent) {

            ...

        }

   }

}

Is there a better way?

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