6

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

user1855222
  • 61
  • 1
  • 1
  • 3
  • [This](http://androidchennai.blogspot.in/2012/05/simple-calendar-control-android.html) is the exact reference you need – Manoj Kumar Nov 27 '12 at 05:18

7 Answers7

4
  • You could create a public method in your DatePickerFragment to return the string.
  • You could have a static variable in your MainActivity that this class writes to.
  • You could use SharedPreferences to store the string.

I would go with the first option, it's the simplest if your application is basic.

There are multiple ways of going about this as you can see, so it's important to look at how the user interacts with your app and when that date is needed. The public return method is nice if you hold a reference to the Fragment in MainActivity and you don't need the data ASAP. The static variable is nice if you need the string changed as soon as the user chooses a date. The last method is wasteful and is least recommended, but there is no static "magic" being done.

A--C
  • 36,351
  • 10
  • 106
  • 92
  • Thanks for the reply . I have to build the string inside the onDataSet method which should be void . How can I pass the generated value to another method ? I tried following public void justShow(){ System.out.println("The date is "+date); } But when I calling justshow() method it out puts date as null , and it executing prior to onDataset method (I do not know why ) . So i am gonna try your second option – user1855222 Nov 27 '12 at 04:39
3

Although this was asked 4years ago and last active 1-year ago (as at my answering). I hope the below helps.

package com.example.fragments;

import java.util.Calendar;

import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.widget.DatePicker;

/**
 * Date picker fragment bit 18/03/2017.
 */

public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {

  private OnDateSetListener callbackListener;

  /**
   * An interface containing onDateSet() method signature.
   * Container Activity must implement this interface.
   */
  public interface OnDateSetListener {
    void onDateSet(DatePicker view, int year, int month, int dayOfMonth);
  }

  /* (non-Javadoc)
   * @see android.app.DialogFragment#onAttach(android.app.Activity)
   */
  @Override
  public void onAttach(Context activity) {
    super.onAttach(activity);

    try {
      callbackListener = (OnDateSetListener) activity;

    } catch (ClassCastException e) {
      throw new ClassCastException(activity.toString() + " must implement OnDateSetListener.");
    }
  }

  @NonNull
  @Override
  public Dialog onCreateDialog(Bundle savedInstanceState) {
    // Use the current date as the default date in the picker
    final Calendar calendar = Calendar.getInstance(getResources().getConfiguration().locale);
    int year = calendar.get(Calendar.YEAR);
    int month = calendar.get(Calendar.MONTH);
    int day = calendar.get(Calendar.DAY_OF_MONTH);

    // Create a new instance of DatePickerDialog and return it
    return new DatePickerDialog(getActivity(), this, year, month, day);
  }

  @Override
  public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    if (callbackListener != null) {
      callbackListener.onDateSet(view, year, month, dayOfMonth);
    }
  }
}

Then do next in MainActivity

    public class MainActivity extends AppCompatActivity implements View.OnClickListener, DatePickerFragment.OnDateSetListener {


  private EditText edittextDate;

  private Locale locale;

  private DialogFragment datePicker;

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

    locale = getResources().getConfiguration().locale;
    datePicker = new DatePickerFragment();

    edittextDate = (EditText) findViewById(R.id.edittextDate);
    edittextDate.setOnClickListener(this);
  }

  @Override
  public void onClick(View v) {
    switch (v.getId()) {

      case R.id.edittextDate: {
        datePicker.show(getSupportFragmentManager(), "datePicker");
        break;
      }
    }
  }

  @Override
  public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
    final Calendar calendar = Calendar.getInstance(locale);
    final DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.MEDIUM, locale);

    if (getCurrentFocus() != null) {
      switch (getCurrentFocus().getId()) {

        case R.id.edittextDate:
          calendar.set(year, month, dayOfMonth);
          edittextDate.setText(dateFormat.format(calendar.getTime()));
          break;
      }
    }
  }
}
OliverTester
  • 401
  • 2
  • 7
  • How we can use an object that implements the ```DatePickerDialog.OnDateSetListener``` instead of use the same activity? – JCarlosR Apr 07 '17 at 05:38
  • @JCarlos, The Activity or Fragment will still need to implement this object (which already implements _DatePickerDialog.OnDateSetListener_). Tried showing this in _ DatePickerFragment_ and _MainActivity_ above. – OliverTester Apr 24 '17 at 10:06
2

Implement a Listener Interface in your activity and pass it to the DatePickerFragment. Then trigger the listener by calling it's methods. It's described here: http://developer.android.com/guide/topics/ui/dialogs.html#PassingEvents

Herrbert74
  • 2,578
  • 31
  • 51
1

Here is how you can get a Date from a DatePickerDialog:

private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
    // onDateSet method
    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
        myday = dayOfMonth;
        mymonth = monthOfYear + 1;
        myyear = year;
        date = String.valueOf(myday) + getString(R.string.iphan) + String.valueOf(mymonth) + getString(R.string.iphan) + String.valueOf(myyear);

        Log.i(TAG,"Date: "+date);
    } 
}; // DatePickerDialog.OnDateSetListener close

@Override
protected Dialog onCreateDialog(int id) {

    switch (id) {
    case DATE_DIALOG_IDdob:
        // Current Calendar Date
    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);
    return new DatePickerDialog(this, mDateSetListener, year, month, day);
    }
    return null;
} // onCreateDialog() close
Josh Lowe
  • 486
  • 3
  • 13
Najib.Nj
  • 3,706
  • 1
  • 25
  • 39
0

Use the below code to return the date in Date-type, in your onDateSet() method

Date date = new Date(int year, int month, int day);
Moses
  • 916
  • 8
  • 14
  • Thanks for the Reply onDateSet() method has to be void (it does not allow me to change ). Therefore I can not return anything from it – user1855222 Nov 27 '12 at 05:05
  • @user1855222 Declare a variable with a public scope in your main activity class. Assign the value inside the onDateSet(). – Moses Nov 27 '12 at 05:10
  • I did it . But when I am calling it still gives NULL I ve included the relevant code from MainActivity in my question after making the change . According to logcat onDateset() executing after , my call for public variable . I don't know the reason – user1855222 Nov 27 '12 at 06:39
0

Declare a public string varibale on the class extnded from the DatePickerDialog class and set the selected date to that public string variable inside th onDataSet method so you can access from your MainActivity through the instance of the DatePickerDialog you created

Hafte
  • 1
0
private void openCalendar() {
DatePickerDialog dialog = new DatePickerDialog(getContext(), (view, year, month, dayOfMonth) -> {

    date = getDateString(year, month, dayOfMonth);

}, mYear, mMonth, mDay);
dialog.show();

}

private String getDateString(int year, int mMonth, int mDay) {
Calendar calendar = Calendar.getInstance();
calendar.set(year, mMonth, mDay);
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
return dateFormat.format(calendar.getTime());

}

  • Please don’t teach the young ones to use the long outdated and notoriously troublesome `SimpleDateFormat` class. At least not as the first option. And not without any reservation. Today we have so much better in [`java.time`, the modern Java date and time API,](https://docs.oracle.com/javase/tutorial/datetime/) and its `DateTimeFormatter`. Yes, you can use it on Android. For older Android see [How to use ThreeTenABP in Android Project](https://stackoverflow.com/questions/38922754/how-to-use-threetenabp-in-android-project). – Ole V.V. Oct 01 '19 at 16:08