0

I'm currently developing an app and in this app you need to be able to pick dates. I've solved this by showing a DatePickerDialog and applying the values to an EditText. My colleague told me I shouldn't create a new object in the function but instead declare it as a variable.

final Calendar c = Calendar.getInstance();
int mYear = c.get(Calendar.YEAR);
int mMonth = c.get(Calendar.MONTH);
int mDay = c.get(Calendar.DAY_OF_MONTH);

DatePickerDialog datePickerDialog = new DatePickerDialog(this,
    new DatePickerDialog.OnDateSetListener() {

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

                startDate.setText(year + "-" +(monthOfYear + 1) + "-" + dayOfMonth);
        }
    }, mYear, mMonth, mDay);

//datePickerDialog.onDateChanged();
datePickerDialog.getDatePicker().setMinDate(System.currentTimeMillis());
datePickerDialog.show();

Is this good practice or would there be a better way to go about this?

Mark Melgo
  • 1,477
  • 1
  • 13
  • 30
  • This is OK .. Alternatively you can create a seperate class to open `DatePickerDialog` and use it throughout the app with a callback interface. – ADM Jul 09 '19 at 06:23
  • Even though `DatePickerDialog` was designed for use with the poorly designed and now long outdated `Calendar` class, I would prefer to use `LocalDate` from [java.time, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) instead. – Ole V.V. Jul 09 '19 at 10:16

2 Answers2

1

Try to this we can create custom date picker to this method:

public class TimePickerDialogCustom extends Dialog implements View.OnClickListener {

public Activity c;
public Dialog d;
public RelativeLayout close;
TextView time;
private Button ok;
private TimePicker timePicker;
int status;
AlexPoppinsLightTextView error_msg_txtView;


public TimePickerDialogCustom(FragmentActivity a, TextView time, int status) {
    super(a);
    this.c = a;
    this.time = time;
    this.status = status;

}


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.pick_time_layout);
    close = findViewById(R.id.closepopup);
    ok = findViewById(R.id.btn_ok_time);
    timePicker = findViewById(R.id.tp_for_activity);

    AppGlobalValidation.hideKeyboard(getContext());


    if (status == 1) {
        SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
        SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
        try {
            Date date = parseFormat.parse(time.getText().toString());
         String time = displayFormat.format(date);            //which is from server;
            String splitTime[] = time.split(":");
            int hours = Integer.parseInt(splitTime[0]);
            int minutes = Integer.parseInt(splitTime[1]);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                timePicker.setHour(hours);
                timePicker.setMinute(minutes);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    } else if (status == 2) {

        SimpleDateFormat displayFormat = new SimpleDateFormat("HH:mm");
        SimpleDateFormat parseFormat = new SimpleDateFormat("hh:mm a");
        try {
            Date date = parseFormat.parse(time.getText().toString());
            String time = displayFormat.format(date);    //which is from server;
            String splitTime[] = time.split(":");
            int hours = Integer.parseInt(splitTime[0]);
            int minutes = Integer.parseInt(splitTime[1]);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                timePicker.setHour(hours);
                timePicker.setMinute(minutes);
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    } 


    error_msg_txtView = findViewById(R.id.error_msg_txtView);
    close.setOnClickListener(this);


    ok.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (status == 1) {
                int hour = timePicker.getCurrentHour();
                int minute = timePicker.getCurrentMinute();

                if (hour >= 0 && hour < 12) {
                    error_msg_txtView.setVisibility(View.GONE);
    time.setText(AppGlobalValidation.convertTo12Hour("" + hour + ":" + "" + minute));
                    AppGlobalValidation.hideKeyboard(getContext());
                    dismiss();

                } else {
                    error_msg_txtView.setVisibility(View.VISIBLE);
                    error_msg_txtView.setText("Please Select Morning");

                }

            } else if (status == 2) {

                int hour = timePicker.getCurrentHour();
                int minute = timePicker.getCurrentMinute();

                if (hour >= 12 && hour < 18) {
                    error_msg_txtView.setVisibility(View.GONE);
    time.setText(AppGlobalValidation.convertTo12Hour("" + hour + ":" + "" + minute));
                    dismiss();
                    AppGlobalValidation.hideKeyboard(getContext());

                } else {
                    error_msg_txtView.setVisibility(View.VISIBLE);
                    error_msg_txtView.setText("Please Select Afternoon ");

                }

            } 
}

@Override
public void onClick(View view) {
    dismiss();
    AppGlobalValidation.hideKeyboard(getContext());
}
 }

After create this methods to call this methods in your activity or fragment:

on click listener to call this methods:

    TimePickerDialogCustom timePickerDialogCustom = new 
    TimePickerDialogCustom(getActivity(), morning_time_txtView, 1);
            timePickerDialogCustom.show();
            timePickerDialogCustom.setCancelable(false);
            timePickerDialogCustom.setCanceledOnTouchOutside(true);
Anand Gaur
  • 225
  • 2
  • 10
0

I suggest

  1. Use LocalDate from java.time, the modern Java date and time API, instead of Calendar. Calendar is poorly designed and long outdated.
  2. Use a formatter for formatting the date text for display. Specifically use a built-in localized format to please the user in some locale.

So your snippet becomes somethiing like this:

    LocalDate today = LocalDate.now(ZoneId.systemDefault());
    int mYear = today.getYear();
    Month mMonth = today.getMonth();
    int mDay = today.getDayOfMonth();

    DatePickerDialog datePickerDialog = new DatePickerDialog(this,
        new DatePickerDialog.OnDateSetListener() {

            @Override
            public void onDateSet(DatePicker view, int year,
                    int monthOfYear, int dayOfMonth) {
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM);
                LocalDate date = LocalDate.of(mYear, monthOfYear + 1, dayOfMonth);
                startDate.setText(date.format(dateFormatter));
            }
        }, mYear, mMonth.getValue() - 1, mDay);

Question: Can I use LocalDate and Month on Android?

Yes, the classes from java.time work nicely on older and newer Android devices. They just require at least Java 6.

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It’s called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bp with subpackages.

Links

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161