Displaying a date picker within a fragment nested inside another fragment

Encountering a slight issue with implementing a Date picker using a fragment into another fragment. Upon clicking the button to load the Date picker, an error message is logged:

java.lang.ClassCastException: com.example.buzzamaid.HomeActivity cannot be cast to android.app.DatePickerDialog$OnDateSetListener
        at com.example.buzzamaid.Fragments.DatePickerFragment.onCreateDialog(DatePickerFragment.java:23)

The assumption is that it's trying to pass it into HomeActivity instead of the DateTimeFragment created. How can this be resolved?

Datepickerfragment Code:


    @NonNull
    @Override
    public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {

        Calendar c = Calendar.getInstance();
        int year =  c.get(Calendar.YEAR);
        int month =  c.get(Calendar.MONTH);
        int day =  c.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getContext(),(DatePickerDialog.OnDateSetListener) getContext(), year, month, day);

    }
}

DateTimeFragment Code:



    Unbinder unbinder;

    @BindView(R.id.bt_select_date)
    Button bt_select_date;

    @BindView(R.id.bt_select_time)
    Button bt_select_time;

    @BindView(R.id.tv_selected_date)
    TextView tv_selected_date;

    @BindView(R.id.tv_selected_time)
    TextView tv_selected_time;



    static DateTimeFragement instance;

    public  static DateTimeFragement getInstance() {
        if (instance == null)
            instance = new DateTimeFragement();
        return instance;

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View itemView =  inflater.inflate(R.layout.fragment_date_time,container,false);
        unbinder = ButterKnife.bind(this,itemView);

        return itemView;

    }

    @OnClick(R.id.bt_select_date)
    public void onClick() {
        DialogFragment datePicker = new DatePickerFragment();
        datePicker.show(getFragmentManager(), "Date Picker");
    }

    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
        Calendar c = Calendar.getInstance();
        c.set(Calendar.YEAR, year);
        c.set(Calendar.MONTH, month);
        c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
        String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
        tv_selected_date.setText(currentDateString);
    }
}

How can the calendar be displayed without crashing when clicking the button in the fragment?

Answer №1

Incorporate OnDateSetListener into your DatePickerFragment, then update the DatePickerDialog instance like so:

return new DatePickerDialog(getContext(), DatePickerFragment.this , year, month, day);

Answer №2

Have you ensured that your HomeActivity is utilizing the

DatePickerDialog.OnDateSetListener
interface? If not, please confirm that your HomeActivity implements the
DatePickerDialog.OnDateSetListener
. By implementing this method, you will have access to an override method.

@Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {

    }

You have the ability to customize this method based on your specific needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What are the reasons for a jQuery function to run in a selective manner?

There seems to be some inconsistency in the behavior of this incomplete script that I'm trying to debug. The issue arises when I click off an item, as sometimes the $(editObj).removeAttr('style'); line of code executes and other times it doe ...

Fetch additional JSON data in a RecyclerView on an Android app

I am working on developing an Android application for a website. The app reads website posts from JSON and displays them in a RecyclerView, showing 10 posts at a time. As the user scrolls through the RecyclerView, the app should load and display the next s ...

What is the most efficient way to apply a class to the post div every 4 seconds using jQuery?

What is the most effective method to dynamically add a class to each div element with a class of "post" every 4 seconds using jQuery? <div class="34 post"> <img width="311" height="417" src="#" class="#" alt="newspapers" /> <h2><a hre ...

Issue with npm configuration permissions

I am encountering permission issues when using the npm config command. It appears that there is an attempt to alter the owner of my ~/.npmrc file without authorization. Upon executing npm config set color false, I encounter the following error: npm ERR! E ...

Fixing 500 (Internal Server Error) in Vue.js and Laravel: The Ultimate Guide

Working on a university project using Vue.js and Laravel, I need assistance with sending information to the API. I'm trying to use axios for the POST request, but it's giving me an error: 500 (Internal Server Error). I can't seem to identif ...

Issue with using jQuery and parseDouble

I have been dealing with an AJAX request that retrieves a JSON object containing multiple values, each with two decimal points. However, the issue is that when these values are returned as part of the JSON, they are in string format. My goal is to perform ...

Ways to determine the total number of npm packages installed, excluding development dependencies

Is there a specific NPM command I can run from the CLI to count only the installed NPM Modules in my package that are not Dev Dependencies? When I use npm ls, it lists all packages without distinguishing between regular dependencies and DevDependencies. ...

Are tabs best displayed as an overlay?

I've been searching high and low for a tutorial on how to create an overlay with tabs similar to the Google Chrome webstore. If anyone knows of a tutorial or a combination of tutorials that can help me achieve this, please let me know! Link Any guida ...

HTML code displaying a fixed message at the top of the webpage

I'm working on a web page that has a lot of content. I need to have a message always visible at the bottom of the browser window, even when scrolling. Can anyone help me achieve this using simple CSS, HTML, jQuery, or PHP? Thanks! ...

A Smarter Approach to Updating Text Dynamically with JavaScript and Vue

Currently, I am utilizing Vue to dynamically update text by using setInterval() in combination with a data property. The method I have in place is functional, but I am curious if there exists a more efficient way to optimize it. Is the current code as stre ...

Guide to transferring a JavaScript/Ajax variable to a PHP webpage with the help of AJAX

function initiateIperfSpeedRequest(speedVar, actualIp) { var xmlhttp = getAjaxObject(); xmlhttp.onreadystatechange = function () { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { handleIperfResponse(xmlhttp.respo ...

Tips for preventing a valid instruction from being identified as an error in NetBeans

As I work on my socket.io and node.js system in NetBeans 7.2, I encounter an issue every time I input a correct instruction like: io.sockets.in(channel_id).emit('new user', data); The problem lies in the ".in" part, which triggers an error high ...

How to stop Mouseenter event from bubbling up in an unordered list of hyperlinks using Vue 3

I've experimented with various methods to prevent event bubbling on the mouseenter event, but I'm still encountering an issue. When I hover over a link, the event is triggered for all the links as if they were all being hovered over simultaneousl ...

"Utilizing Bootstrap Tour for Easy Navigation: Automatically Scroll Back to the Top with

I have a Bootstrap tour set up with code that is meant to capture the user pressing the end tour button and scroll them back to the top of the screen. However, currently the code runs when a new popover loads instead of when the end tour button is clicke ...

What is the best way to remove a selected item from an array in Vuejs when it has been clicked

I'm having trouble with my splice() method in this simple To-Do app. I want to delete a specific task by clicking a button, but the solutions I've tried from Stack Overflow aren't working for me. The items do get deleted, but only the last o ...

Executing MongoDB collection operations with array filtering

I am looking to count records based on tags and filter them before including in specific groups // data in database {tags: ['video', 'Alex'], ... }, {tags: ['video', 'John'], ... }, {tags: ['video', 'J ...

Passing props to children in the Next JS Layout component is a crucial aspect of

I recently came across a code snippet that effectively resolved my re-rendering issue in Next JS when switching pages. However, I am now faced with the challenge of sending props to the children component. In my layout.js file, I have managed to send props ...

Discovering the art of interpreting the triumphant outcome of an Ajax request with jquery/javascript

I recently encountered a challenge with my function that deals with a short JSON string: <script id="local" type="text/javascript"> $( document ).ready(function() { $('tr').on('blur', 'td[contenteditable]', functi ...

Having trouble with Jquery's .mouseover() method? Let's catch the solution!

I'm currently working on a jQuery homework assignment and I've been attempting to enhance the mouseover feature, but unfortunately, it's not functioning as expected. $("button").mouseover(function() { $(this).css({ left: (Math.rando ...

"Exploring the process of looping through a JSON object following an asynchronous retrieval of JSON data using

I am facing an issue while trying to iterate through a JSON object in jQuery after fetching it asynchronously. I have a function called 'listFiles' that uses async to successfully retrieve a file list from a directory (dir) by calling an API endp ...