I have a fragment containing a cusom layout and an event listener to handle the user interaction with the custom view. But I get a null pointer exception on setting the event listener inside the fragment. Here, I found that the custom view reference is null in the fragment.
public class CustomCalendarView extends LinearLayout {
private EventListener eventListener;
public CustomCalendarView(Context context, AttributeSet attrs)
{
super(context);
............
cellView = (GridView) findViewById(R.id.calendar_grid);
cellView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
if (eventListener == null)
return false;
eventListener.onDayLongPress((Date) adapterView.getItemAtPosition(i));
return true;
}
});
}
public void setEventListener(EventListener eventListener) {
this.eventListener = eventListener;
}
public interface EventListener {
void onDayLongPress(Date date);
}
}
public class DescribeFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.inflate(R.layout.fragment_explore_planner, container, false);
MainActivity activity = (MainActivity) getActivity();
customCalendarView = ((CustomCalendarView) view.findViewById(R.id.calendar_view));
customCalendarView.setEventListener(new CustomCalendarView.EventListener() {
@Override
public void onDayLongPress(Date date) {
Toast.makeText(getContext(), timeFormatter.format(date), Toast.LENGTH_SHORT).show();
}
});
}
I found that I hadn't called super(context, attrs) from the constructor of the Custom View. Changing super(context) to super(context, attrs) within the constructor having context and attrs as their parameters have resoved my issue.