Search code examples
javaandroid-studiomethodsandroid-activityfragment

I can't create a CalendarView inside a Fragment


Good afternoon, I'm new to Android Studio development. I'm developing an application where I need to create a Calendar in one of the Fragments.

I'm trying to create a CalendarView in my fragment, but the setContentView methods and others are highlighted in red, what am I doing wrong? Below is the code.

public class CalendarFragment extends Fragment  {
    private CalendarView calendarView;

    public CalendarFragment() {
        // Required empty public constructor
    }
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_calendar);
        CalendarView calendarView = findViewById(R.id.calendarView);
        calendarView.setOnDateChangeListener(new OnDateChangeListener() {

            @Override
            public void onSelectedDayChange(CalendarView view, int year,
                                            int month, int dayOfMonth) {
                int mYear = year;
                int mMonth = month;
                int mDay = dayOfMonth;
                String selectedDate = new StringBuilder().append(mMonth + 1)
                        .append("-").append(mDay).append("-").append(mYear)
                        .append(" ").toString();
                Toast.makeText(getApplicationContext(), selectedDate, Toast.LENGTH_LONG).show();
            }
        });
    }
}

Solution

  • You can try like this

     @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
    
    
        }
    
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
    
            View view1 = inflater.inflate(R.layout.fragment_calendar, container, false);
            calendarView = view1.findViewById(R.id.calendarView);
            calendarView.setOnDateChangeListener((view, year, month, dayOfMonth) -> {
                int mYear = year;
                int mMonth = month;
                int mDay = dayOfMonth;
                String selectedDate = new StringBuilder().append(mMonth + 1)
                        .append("-").append(mDay).append("-").append(mYear)
                        .append(" ").toString();
                Toast.makeText(getContext(), selectedDate, Toast.LENGTH_LONG).show();
            });
    
    
            return view1;
    
        }
    

    Here you need to get CalendarView in onCreateView and return view1 otherwise you get java.lang.NullPointerException: Error Like View view1 = inflater.inflate(R.layout.fragment_calendar, container, false);