Get Date from Datepicker Using Dialogfragment

Get date from datepicker using dialogfragment

Constructor fo DatePickerDialog takes DatePickerDialog.OnDateSetListener as second parameter, so maybe you should implement that interface in your parent activity EditSessionActivity (not in DatePickerFragment ) and change this line:

return new DatePickerDialog(getActivity(), this, year, month, day);

into this:

return new DatePickerDialog(getActivity(), (EditSessionActivity)getActivity(), year, month, day);

And then your activity should looks like this:

public class EditSessionActivity extends FragmentActivity implements
DatePickerDialog.OnDateSetListener{

public void onDateSet(DatePicker view, int year, int month, int day) {
//use date in your activity
}
...
}

Android DialogFragment - Get reference to date picker

I sorted this out with the help of this StackOverflow answer:

public void showDatePickerDialog() {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
getFragmentManager().executePendingTransactions(); // commits the show method from above
DatePickerDialog dialog = (DatePickerDialog) newFragment.getDialog();
DatePicker datePicker = (DatePicker) dialog.getDatePicker();
Date now = new Date();
datePicker.setMaxDate(now.getTime());
}

You need to call .executePendingTransactions()on the fragment manager to stop the dialog fragment being added asynchronously, otherwise the getDialog() method gives a null pointer exception.

I am putting it in here for anyone in the future who may have this problem.

Set DatePicker DialogFragment to specific date

I figured it out. Pretty simple actually. To pass data to a fragment you use a bundle. I changed the call to the fragment to add a bundle containing the initial date like so:

        dob.Click += (sender, e) =>
{
Bundle bundlee = new Bundle();
bundlee.PutString("initDate", dob.Text);
DatePickerFragment frag = DatePickerFragment.NewInstance(delegate (DateTime time)
{
string thedate = time.ToShortDateString();
if (Utils.Mid(thedate,2,1) == "/")
{
thedate = "0" + thedate;
}
dob.Text = thedate;
});
frag.Arguments = bundlee;
frag.Show(SupportFragmentManager, DatePickerFragment.TAG);
};

Then in the OnCreateDialog method of the fragment I get the data from the bundle and set the initial date of the date picker, like so:

    public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
Bundle bundlee = this.Arguments;
int month = DateTime.Now.Month;
int day = DateTime.Now.Day;
int year = DateTime.Now.Year;
string initDate = bundlee.GetString("initDate");
if (initDate != "" && initDate != null)
{
month = Convert.ToInt32(Utils.Mid(initDate, 1, 2));
day = Convert.ToInt32(Utils.Mid(initDate, 4, 2));
year = Convert.ToInt32(Utils.Mid(initDate, 7, 4));

}

//DateTime currently = DateTime.Now;
DatePickerDialog dialog = new DatePickerDialog(Activity,
this,
year,
month - 1,
day);

return dialog;
}

Being a lifelong VB programmer starting with VB4, I just couldn't do without the Mid function, so I created an equivalent in c# and put it in my Utils class (in case you're wondering where that comes from):

class Utils
{
public static string Mid(string input, int index, char newChar)

{

if (input == null)

{

throw new ArgumentNullException("input");

}

char[] chars = input.ToCharArray();

chars[index - 1] = newChar;

return new string(chars);

}
public static string Mid(string s, int a, int b)

{

string temp = s.Substring(a - 1, b);

return temp;

}
}

Setting date using DialogFragment and Android Annotations

The Click annotation is just for triggering the dialog.
You should implement a callback method through listener interfaces described here:
http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents

EDIT: I implemented a version for myself, here is the code:

MainActivity.java:

    package com.example.datepickerexample;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;

import com.example.datepickerexample.DatePickerFragment.DatePickerDialogListener;

public class MainActivity extends FragmentActivity implements
DatePickerDialogListener {
TextView lbl_from, lbl_to, cpn_from, cpn_to;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cpn_from = (TextView) findViewById(R.id.cpn_from);
cpn_to = (TextView) findViewById(R.id.cpn_to);
lbl_from = (TextView) findViewById(R.id.lbl_from);
lbl_to = (TextView) findViewById(R.id.lbl_to);
}

public void showFromDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
Bundle bundle = new Bundle();
bundle.putBoolean("isFromDate", true);
newFragment.setArguments(bundle);
newFragment.show(getSupportFragmentManager(), "datePicker");
}

public void showToDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
Bundle bundle = new Bundle();
bundle.putBoolean("isFromDate", false);
newFragment.setArguments(bundle);
newFragment.show(getSupportFragmentManager(), "datePicker");
}

@Override
public void onDatePicked(DialogFragment dialog, Calendar c,
boolean isFromDate) {
String strdate = null;

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");

if (c != null) {
strdate = sdf.format(c.getTime());
}
if (isFromDate) {
lbl_from.setText(strdate);
} else {
lbl_to.setText(strdate);
}
}

}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >

<TextView
android:id="@+id/cpn_from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_margin="6dp"
android:text="@string/from_date" />

<TextView
android:id="@+id/lbl_from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@id/cpn_from"
android:layout_toRightOf="@id/cpn_from" />

<Button
android:id="@+id/btn_from"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/cpn_from"
android:onClick="showFromDatePickerDialog"
android:text="@string/pick_from_date" />

<TextView
android:id="@+id/cpn_to"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn_from"
android:layout_margin="6dp"
android:text="@string/to_date" />

<TextView
android:id="@+id/lbl_to"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/btn_from"
android:layout_alignBaseline="@id/cpn_to"
android:layout_toRightOf="@id/cpn_to" />

<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/cpn_to"
android:onClick="showToDatePickerDialog"
android:text="@string/pick_to_date" />

</RelativeLayout>

DatePickerFragment.java:

package com.example.datepickerexample;

import java.util.Calendar;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;

public class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {

public interface DatePickerDialogListener {
public void onDatePicked(DialogFragment dialog, Calendar c,
boolean isFromDate);
}

// Use this instance of the interface to deliver action events
DatePickerDialogListener mListener;

boolean isFromDate;

public static DatePickerFragment newInstance(boolean isFromDate) {
DatePickerFragment instance = new DatePickerFragment();

instance = new DatePickerFragment();
Bundle args = new Bundle();
args.putBoolean("isFromDate", isFromDate);
instance.setArguments(args);
return instance;
}

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
isFromDate = getArguments().getBoolean("isFromDate");
}

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);

// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}

public void onDateSet(DatePicker view, int year, int month, int day) {
Calendar c = Calendar.getInstance();

c.set(year, month, day);
mListener.onDatePicked(this, c, isFromDate);
}

// Override the Fragment.onAttach() method to instantiate the
// NoticeDialogListener
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// Verify that the host activity implements the callback interface
try {
// Instantiate the NoticeDialogListener so we can send events to the
// host
mListener = (DatePickerDialogListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
}

Several questions about DatePickerDialog using DialogFragment

For your first question, you can set min date and max date inside onCreateDialog:

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
val c = Calendar.getInstance()
val year = c.get(Calendar.YEAR)
val month = c.get(Calendar.MONTH)

val day = c.get(Calendar.DAY_OF_MONTH)
val d = DatePickerDialog(requireActivity(), this , year, month, day)
val dp = d.datePicker

dp.maxDate = //Do your calculation
dp.min= //Do your calculation

return d
}

And for your other question - you can implement the DatePickerDialog.OnDateSetListener inside your main fragment and call onDateSet from there

showing a DatePickerDialog inside a Dialogfragment

The solution isn't about the datepickerdialog at all. I had a switch-case in my fragment that manages the events of clicks. I accidentally forgot to put a break; after the case which caused a flow to the other events (one of them was dismiss();), and that's why the datepickerdialog also dismissed my fragment.

Open a DatePicker From DialogFragment

DialogFragment is not an Activity, that's why you get ActivityNotFoundException.

You should do something like this in your onClick() method:

DatePicker_from dialogFragment = new DatePicker_from();
dialogFragment.show(getFragmentManager(), "tag");

Retrieve and set data from DialogFragment (DatePicker)

In the method in your DialogFragment that is in charge of being notified when the user sets the date, do this

Button activityButton = (Button)getActivity().findViewById(R.id.myButton);
activityButton.setText (myDate);


Related Topics



Leave a reply



Submit