Created
August 19, 2013 09:20
-
-
Save liminal/6267246 to your computer and use it in GitHub Desktop.
Avoiding null pointer exceptions when passing events back from fragment to activity
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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