Skip to content

Instantly share code, notes, and snippets.

@liminal
Created August 19, 2013 09:20
Show Gist options
  • Save liminal/6267246 to your computer and use it in GitHub Desktop.
Save liminal/6267246 to your computer and use it in GitHub Desktop.
Avoiding null pointer exceptions when passing events back from fragment to activity
package com.example;
import android.app.Activity;
public class MyActivity extends Activity
implements MyFragment.Callbacks {
@Override
public void onItemClick(Object object) {
//Do thing with the passed object
}
}
package com.example;
import android.app.Activity;
import android.app.ListFragment;
public class MyFragment extends ListFragment {
private Callbacks mCallbacks = sDummyCallbacks;
private static Callbacks sDummyCallbacks = new Callbacks() {
@Override
public void onItemClick(Object object) {
//Do nothing
}
};
public interface Callbacks {
public void onItemClick(Object object);
}
public void onWhateverEventWeAreDealingWith() {
mCallbacks.onItemClick(someObject);
}
/*
* We switch between the dummy callbackhandler and the host activity as callback handler
* when the fragment attaches or detaches from the activity, thus we don't have to worry
* when we call the callbacks whether activity is null or not. Callbacks will always be
* valid
*
*/
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (! (activity instanceof Callbacks))
throw new IllegalStateException("Host activity for MyFragment must implement MyFragment.Callbacks");
mCallbacks = (Callbacks) activity;
}
@Override
public void onDetach() {
mCallbacks = sDummyCallbacks;
super.onDetach();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment