Reputation: 415
I have managed to make a date picker class but now I want the value from the date picker dialog to be returned to the main activity class. Below is the code for the date picker dialog.
public class DateChooser extends DialogFragment implements DatePickerDialog.OnDateSetListener{
public int y,m,d;
public Dialog onCreateDialog(Bundle savedInstanceState)
{
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(getContext(),this,year,month,day);
}
@Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Toast.makeText(getContext(), "Toast!", Toast.LENGTH_SHORT).show();
setDay(dayOfMonth);
setMonth(month);
setYear(year);
}
I have called this class from the mainactivity.
public void dateSelect(View view)
{
DateChooser dateC = new DateChooser();
dateC.show(getSupportFragmentManager(),"tag");
}
Upvotes: 1
Views: 882
Reputation: 234
Do this:
Add this to DateChooser Class:
private DateSelectedListener mListener;
@Override
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
mListener.onDateSelected(view, year, month, day);
}
public void display(FragmentManager manager, String tag, DateSelectedListener listener) {
super.show(manager, tag);
mListener = listener;
}
public interface DateSelectedListener {
void onDateSelected(DatePicker view, int year, int month, int day);
}
in your Activity do this:
public class MyActivity extends AppCompatActivity implements DateChooser.DateSelectedListener {
//onCreate or whatever other method:
dateChooser.display(
getActivity().getSupportFragmentManager(),
"datePicker", this);
}
Good luck!!!
Upvotes: 1
Reputation: 1642
You can create an interface e.g. like this
public interface DateListener {
void onDateSelected(int day, int month, int year);
}
and implement it in your activity
public class YourActivity extends Activity implements DateListener {...}
then you have to implement the method in your activity...
In your Fragment
add the following field:
private DateListener dateListener;
and add this code to your Fragment's onAttach
:
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (!(getActivity() instanceof DateListener)) {
throw new ClassCastException("The activity inflating this fragment must implement DateListener!");
}
dateListener = (DateListener) getActivity();
}
Now you have set your activity as DateListener and can use it in the result of the DatePicker
Upvotes: 0
Reputation: 2668
DatePicker datePicker = (DatePicker) findViewById(R.id.datePicker1);
int day = datePicker.getDayOfMonth();
int month = datePicker.getMonth() + 1;
int year = datePicker.getYear();
String dateInString=year+"-"+month+"-"+day;
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
Date date = formatter.parse(dateInString);
System.out.println(date);
Upvotes: 0