Reputation: 389
I want using AlertDialog to show calendar when I touch on Edit Text in fragment. In the past, when i using Activity class, it worked perfect. But when I using Fragment, It is not working.
Here is method to show calendar dialog when touch edit text in Fragment:
private void setDateTimeField() {
try {
et_date.setOnClickListener(this);
final Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth - 1);
if (newDate.getTime().getTime() > (newCalendar.getTime().getTime())) {
final AlertDialog builder = new AlertDialog.Builder(getActivity()).setTitle("Notification").setMessage("This is a date of future! We will get current date for this review!").show();
//this code below is coppied in https://xjaphx.wordpress.com/2011/07/13/auto-close-dialog-after-a-specific-time/
final Timer t = new Timer();
t.schedule(new TimerTask() {
public void run() {
builder.dismiss(); // when the task active then close the dialog
t.cancel(); // also just top the timer thread, otherwise, you may receive a crash report
}
}, 2000); // after 2 second (or 2000 miliseconds), the task will be active.
et_date.setText(dateFormatter.format(newCalendar.getTime()));
} else {
newDate.set(year, monthOfYear, dayOfMonth);
et_date.setText(dateFormatter.format(newDate.getTime()));
}
}
}, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
} catch (Exception ex) {
messages("Something Wrong!");
}
}
It's wrong at:
final AlertDialog builder = new AlertDialog.Builder(getActivity()).setTitle("Notification").setMessage("This is a date of future! We will get current date for this review!").show();
When i remove final for builder, this code above is ok, but other problem appear at:
builder.dismiss();
This code above requires builder must be final. I know the best solution for my question is using DialogFragment. But I don't want using it. Moreover, I want know the reason for this error. Please help me. p/s: My english is not good so I'm so sorry if i have any wrong in grammar and thanks you for reading my question.
Upvotes: 1
Views: 107
Reputation: 7083
Change
fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {
to
fromDatePickerDialog = new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener() {
Upvotes: 5