How to return the date value from DatePickerDialog in Android?
- by user1855222
I am new to android . I ve created a Date picker in android using following guide .http://developer.android.com/guide/topics/ui/controls/pickers.html
public class DatePickerFragment extends DialogFragment
implements DatePickerDialog.OnDateSetListener {
StringBuilder sb = new StringBuilder();
public static String date;
@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) {
// Do something with the date chosen by the user
sb.append(year);
sb.append('-');
sb.append(month+1);
sb.append('-');
sb.append(day);
date = sb.toString();
System.out.println("The date is "+date);
}
I need to return this date value (date = sb.toString()) to my MainActivity . Since the onDateSet method is void what should I do ?
Additional Information - DatePickerDialog Triggers at the MainActivity class ,But not with single button click . There are several processes happens in side a single button , Date picker will triggers only when certain condition is met . I do not want to display the date value either . Just want it returned for further processing.
Appreciate any kind of guidance
Changed onDataset method and justshow()
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
sb.append(year);
sb.append('-');
sb.append(month+1);
sb.append('-');
sb.append(day);
date = sb.toString();
MainActivity.newdate=sb.toString();
System.out.println("The date is "+MainActivity.newdate);
}
public void justShow(){
System.out.println("The date is "+MainActivity.newdate);
}
This is the relevant Part From Main(After making changes suggested in first reply )
DateToken mydate=new DateToken();
String test=dayvals.get(0);
DialogFragment df=new DatePickerFragment();
if(test.equalsIgnoreCase("day")){
df.show(getSupportFragmentManager(), "DatePik");
}
System.out.println("Date is on Main"+newdate);
DatePickerFragment dpf=new DatePickerFragment();
dpf.justShow();
newdate is the static String , but still outputs null. In both MainActivity and justShow methods . But in onDataSet method date outputs correctly