1
\$\begingroup\$

I currently have an Android Activity that allows the users to select the startDate, endDate, startTime and endTime. Once they click the "submit" button, I will combine the startDate and startTime together, and then convert it to milliseconds. The milliseconds will then be used to set an alarm using the AlarmManager. So far, I was able to convert the startDate and startTime to milliseconds. However, I feel that there are far better solutions out there, which I am not aware of.

Here is the screenshot of my layout and my Java code:

enter image description here

MainActivity

public class MainActivity extends AppCompatActivity implements DatePickerDialog.OnDateSetListener,
    TimePickerDialog.OnTimeSetListener, View.OnClickListener {

private TextView txtStartDate;
private TextView txtEndDate;
private TextView txtStartTime;
private TextView txtEndTime;
private Button btnSubmit;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    txtStartDate = findViewById(R.id.txtStartDate);
    txtEndDate = findViewById(R.id.txtEndDate);
    txtStartTime = findViewById(R.id.txtStartTime);
    txtEndTime = findViewById(R.id.txtEndTime);
    btnSubmit = findViewById(R.id.btnSubmit);

    txtStartDate.setOnClickListener(this);
    txtEndDate.setOnClickListener(this);
    txtStartTime.setOnClickListener(this);
    txtEndTime.setOnClickListener(this);
    btnSubmit.setOnClickListener(this);

}

@Override
public void onClick(View v) {
    switch (v.getId()) {
        case R.id.txtStartDate:
            /* You need to define a unique tag name for each fragment */
            createDialogFragment("StartDatePicker");
            break;
        case R.id.txtEndDate:
            createDialogFragment("EndDatePicker");
            break;
        case R.id.txtStartTime:
            createDialogFragment("StartTimePicker");
            break;
        case R.id.txtEndTime:
            createDialogFragment("EndTimePicker");
            break;
        case R.id.btnSubmit:
            retrieveInput();
    }
}

private void createDialogFragment(String tag) {
    /* getSupportFragmentManager() will return a FragmentManager
     * that is used to manage the fragments */
    if (tag.equals("StartDatePicker") || tag.equals("EndDatePicker")) {
        DialogFragment datePicker = new DatePickerFragment();
        datePicker.show(getSupportFragmentManager(), tag);
    } else {
        DialogFragment timePicker = new TimePickerFragment();
        timePicker.show(getSupportFragmentManager(), tag);
    }
}

@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());

    FragmentManager fragmentManager = getSupportFragmentManager();
    if (fragmentManager.findFragmentByTag("StartDatePicker") != null) {
        txtStartDate.setText(currentDateString);
    } else {
        txtEndDate.setText(currentDateString);
    }
}

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    Calendar c = Calendar.getInstance();
    c.set(Calendar.HOUR_OF_DAY, hourOfDay);
    c.set(Calendar.MINUTE, minute);

    String currentTimeString = DateFormat.getTimeInstance(DateFormat.SHORT).format(c.getTime());

    FragmentManager fragmentManager = getSupportFragmentManager();
    if (fragmentManager.findFragmentByTag("StartTimePicker") != null) {
        txtStartTime.setText(currentTimeString);
    } else {
        txtEndTime.setText(currentTimeString);
    }
}

private void retrieveInput() {
    /* Get the startDate and startTime and covert it to milliseconds */
    String date = txtStartDate.getText().toString();
    String time = txtStartTime.getText().toString();
    String datetime = date + " " + time;
    SimpleDateFormat df = new SimpleDateFormat("EEEE, MMMM d, yyyy hh:mm a");
    Date date1 = null;
    long milli = 0;
    try {
        date1 = df.parse(datetime);
        milli = date1.getTime();

    } catch (ParseException e) {
        e.printStackTrace();
    }
    Toast.makeText(this, "" + milli, Toast.LENGTH_SHORT).show();
}
}

activity_main.xml

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity"
tools:layout_editor_absoluteY="81dp">

<TextView
    android:id="@+id/txtStartDate"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="48dp"
    android:layout_marginLeft="48dp"
    android:layout_marginTop="136dp"
    android:text="Start Date"
    android:textSize="16sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/txtEndDate"
    android:layout_width="wrap_content"
    android:layout_height="27dp"
    android:layout_marginStart="48dp"
    android:layout_marginLeft="48dp"
    android:layout_marginTop="36dp"
    android:text="EndDate"
    android:textSize="16sp"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtStartDate" />

<TextView
    android:id="@+id/txtStartTime"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="136dp"
    android:layout_marginEnd="56dp"
    android:layout_marginRight="56dp"
    android:text="Start Time"
    android:textSize="16sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<TextView
    android:id="@+id/txtEndTime"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginTop="40dp"
    android:layout_marginEnd="60dp"
    android:layout_marginRight="60dp"
    android:text="End Time"
    android:textSize="16sp"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/txtStartTime" />

<Button
    android:id="@+id/btnSubmit"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_marginStart="8dp"
    android:layout_marginLeft="8dp"
    android:layout_marginEnd="8dp"
    android:layout_marginRight="8dp"
    android:layout_marginBottom="192dp"
    android:text="Submit"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent" />

</android.support.constraint.ConstraintLayout>

DatePickerFragment.java

public class DatePickerFragment extends DialogFragment {

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    // Get the current time and use it as the default values for the picker
    Calendar c = Calendar.getInstance();
    int year = c.get(Calendar.YEAR);
    int month = c.get(Calendar.MONTH);
    int day = c.get(Calendar.DAY_OF_MONTH);
    int hour = c.get(Calendar.HOUR_OF_DAY);
    int minute = c.get(Calendar.MINUTE);

    // Create and return an instance of the DatePickerDialog
    return new DatePickerDialog(getActivity(),
            (DatePickerDialog.OnDateSetListener) getActivity(),
            year, month, day);

TimePickerFragment.java

public class TimePickerFragment extends DialogFragment {

@NonNull
@Override
public Dialog onCreateDialog(@Nullable Bundle savedInstanceState) {
    Calendar c = Calendar.getInstance();
    int hour = c.get(Calendar.HOUR_OF_DAY);
    int minute = c.get(Calendar.MINUTE);

    return new TimePickerDialog(getActivity(),
            (TimePickerDialog.OnTimeSetListener) getActivity(),
            hour, minute, DateFormat.is24HourFormat(getActivity()));
}
}
\$\endgroup\$
  • \$\begingroup\$ Have you considered merging your 2 dialogs into 1 DateTimePickerdialog? Also you might want to take a look at the various classes and methods in the java.time api. \$\endgroup\$ – tinstaafl Jan 3 at 2:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.