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

Set the Vue 3 Select-Option to automatically select the first option as the default choice

I am attempting to set the first select option as the default, so it shows up immediately when the page loads. I initially thought I could use something simple like index === 0 with v-bind:selected since it is a boolean attribute to select the first option ...

How to Implement Button Disable Feature in jQuery When No Checkboxes Are Selected

I need help troubleshooting an issue with a disabled button when selecting checkboxes. The multicheck functionality works fine, but if I select all items and then deselect one of them, the button disables again. Can someone assist me with this problem? Be ...

Sending data using formData across multiple levels of a model in Angular

I have a model that I need to fill with data and send it to the server : export interface AddAlbumeModel { name: string; gener: string; signer: string; albumeProfile:any; albumPoster:any; tracks:TrackMode ...

Different ways to showcase a value from the CSS file on the console using console.log

In this guide, you can learn how to create a custom directive in Angular by following this tutorial: Custom Directive Tutorial. The directive should function as intended. Still, I want to see the color value set in the CSS file displayed on the console us ...

Is your window.location.hash malfunctioning?

I am facing an issue with changing the background color of a <div id="services> when a specific link (index.html#services) is clicked. I have attempted to use the latest jQuery along with the jQuery Color plugin from jQuery Color. The code snippet I ...

Issue with redirecting to another link in Angular routing

After numerous attempts, I finally managed to configure the adviceRouterModule correctly. Despite extensive research and Google searches, I couldn't quite crack it. Here is the configuration for my AdviceRoutingModule: const adviceRouters: Routes = ...

Exploring Ngu-Carousel in Angular 7: Importing JSON data for a dynamic display

After attempting to import data from JSON and display it using ngu-carousel, I encountered an error. The error shows "length of undefined" Subsequently, when I try to click on the previous/next button, another error appears. This error states "innerHTML ...

Include an external JavaScript file within a component to display pictures in a web browser using Angular 2

I am developing a website using Angular 2 and need to incorporate a JavaScript file into a component. The goal is for this script to adjust the height of certain images to match the height of the browser window. What is the best way to integrate this scri ...

Top choice for developing real-time multiplayer 2D cross-platform games

I am working on creating a 2D multiplayer game similar to agar.io that will be available for Android, iOS, and web platforms. Each room in the game will have a limit of 30 players. After some research, I have identified a few possible options for developin ...

Ways to enhance focus on childNodes using Javascript

I am currently working on implementing a navigation system using a UL HTML Element. Here's the code I have so far: let htmlUL = <HTMLElement>document.getElementById('autocomplete_ul_' + this.name); if (arg.keyCode == 40) { // down a ...

"Incorporate countless Bootstrap 4 carousels into one webpage for an enhanced user

I'm experiencing difficulties with the new Bootstrap 4. Can anyone provide guidance on how to incorporate multiple Bootstrap carousels into a single page? I've researched several websites, but most only offer solutions for Bootstrap 3. Your assi ...

Get rid of numerous div elements in a React.js application with the help of a Remove button

I need help figuring out how to efficiently remove the multiple div's that are generated using the add button. I am struggling to grasp how to pass the parent div's id into the delete method from the child div. Additionally, I'm wondering if ...

The function $http.get in AngularJS is providing an undefined response

In the process of developing a small Angular application, I started with this seed project: https://github.com/angular/angular-seed. The only modifications I made were to the following files: /app/view1/view1.js 'use strict'; angular.mod ...

A step-by-step guide on incorporating box-shadow for the jackColor in the Switchery Plugin

I am looking to add a box shadow to my iOS7 style switches for checkboxes when they are checked. Here is the code I have so far: var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { va ...

Is AjaxMin's EvalTreatment changing the game for JavaScript minification?

While minifying my project using the AjaxMin.dll with the default settings on every build/deployment, I ran into a problem. One of our third-party JavaScript files contains an eval statement that references variables or parameters which, when minified, cau ...

Utilizing a Chrome packaged app to interact with a local sqlite database through reading and writing operations

Is it feasible to access and manipulate a local sqlite database from within a Chrome packaged app? I am currently able to work with a locally stored JSON file for my app data, but now I also require the functionality to interact with a sqlite database in ...

Guide to emitting a value using the composition API

I'm currently working with a datepicker component that is part of a form in my Vue3 app using the composition API. My challenge is how to pass a value from the datepicker component back up to the form component. Unfortunately, I've encountered ...

Updates to $scope are not reflecting in the application

My input includes a datalist that is populated by an angular get request as the page loads. <input list="data" /> <datalist id="data"> <option ng-repeat="item in items" value="{{item.data}}"> </datalist> The $http call is straig ...

WebSocket connection established on port 8888, while the web server is running on port 80 - incompatible to merge the two services

Here is some node.js server-side code that involves watching a file and sending modifications to the browser: var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') a ...

The Material UI Drawer is fading into the background instead of smoothly sliding into view

Seeking guidance as a novice in SD, I am dedicating my free time to honing my skills. Any advice is appreciated, but please explain it as if I were a child. My current endeavor involves making the Drawer Component feature functional and customizing it to s ...