How to return the date value from DatePickerDialog in Android?

Posted by user1855222 on Stack Overflow See other posts from Stack Overflow or by user1855222
Published on 2012-11-27T04:10:29Z Indexed on 2012/11/27 5:04 UTC
Read the original article Hit count: 274

Filed under:
|

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

© Stack Overflow or respective owner

Related posts about android

Related posts about datepicker