Skip to content Skip to sidebar Skip to footer

How To Update Data Inside Fragment From Parent Acitivity

I have the design like this: ----------------------------------- | search input | spinner | ----------------------------------- | item 1 | | item

Solution 1:

You can make an interface and have the Activity implement it. The overriden functions would be the ones which return real time data (in form of HashMap or array as per your design).

@OverridepublicDataTypegetMyData()
    {
       ....
        return latestFilteredData;
    }

In fragment onAttach callback, initialize interface's object.

@OverridepublicvoidonAttach(Activity activity){
    callback = (MyInterface) activity;

    super.onAttach(activity);
}

Now you can use callback object to get latest data anywhere in activity like:

 callback.getMyData();

Solution 2:

Solution 3:

Use otto from square

It is simply awesome event bus library for android. It will keep your code loosely coupled and clean.

Example usage:

//posting a event from your activityBusbus=newBus();
bus.post(newAnswerAvailableEvent(42));

//receiving event in your fragment@SubscribepublicvoidanswerAvailable(AnswerAvailableEvent event) {
    // TODO: React to the event somehow!
}
bus.register(this);

Post a Comment for "How To Update Data Inside Fragment From Parent Acitivity"