I am using the DatePicker
for my application. I want to get the date that I have selected (on the DatePicker
), but it\'s not returning the selected
there's also a great tutorial here which also has source code to download.
One thing to note, when compiling the source code, you need make SelectDateFragment class "static" in javapapers code as well as make populateSetDate() method static, and I also moved this code:
mEdit = (EditText)findViewById(R.id.editText1);
to the onCreate() method. After that you could be able to compile the code.
MainActivity should look like this in the end after editing:
package com.javapapers.andoiddatepicker;
import java.util.Calendar;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
public class MainActivity extends FragmentActivity {
private static EditText mEdit;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mEdit = (EditText) findViewById(R.id.editText1);
}
public void selectDate(View view) {
DialogFragment newFragment = new SelectDateFragment();
newFragment.show(getSupportFragmentManager(), "DatePicker");
}
public static void populateSetDate(int year, int month, int day) {
mEdit.setText(month + "/" + day + "/" + year);
}
public static class SelectDateFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
@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) {
populateSetDate(year, month+1, day);
}
}
}