Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dummy callback interface

In the example master-detail-flow code from Google that Eclipse creates for you, theres this stuff in the fragment:

private Callbacks mCallbacks = sDummyCallbacks;

public interface Callbacks {
    public void onItemSelected(String id);
}

private static Callbacks sDummyCallbacks = new Callbacks() {
    @Override
    public void onItemSelected(String id) {
    }
};


@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    mCallbacks = (Callbacks) activity;
}

@Override
public void onDetach() {
    super.onDetach();
        // Reset the active callbacks interface to the dummy implementation.
    mCallbacks = sDummyCallbacks;
}

I understand how a callback interface is used to communicate from a fragment to it's containing Activity, but what is this dummy callback good for?

like image 542
fweigl Avatar asked Jun 06 '13 07:06

fweigl


1 Answers

The dummy callback is made to avoid the need for testing the validity of the callback when using it.

The other way to 'reset' the callbacks in onDetach is to set it to null, but that would require null testing every time it is used, which is a lot of repetitive/boring code.

like image 143
njzk2 Avatar answered Sep 19 '22 13:09

njzk2