DatePickerDialog result back to Fragment? - android

I want to get the selected Date from the DatePickerDialog back to my Fragment.
Whe i test it, i only get in the Build Log this Error:
E/ViewRootImpl: sendUserActionEvent() mView == null
Testing my code on an Samsung Galaxy S6 Edge (7.0)
The Dialog appears, i can choose a date, click on ok but dont get the result to my TextView... Did i forget a little detail??
My Fragment where i call the DatePickerDialog:
package at.marcelklein.drautaxi;
import android.app.DatePickerDialog;
import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import java.text.DateFormat;
import java.util.Calendar;
/**
* Created by Marcel on 10.09.2017.
*/
public class FourthFragment extends Fragment implements DatePickerDialog.OnDateSetListener {
View myView;
TextView textView;
Button btnDayStart, btnDayEnd;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fourth_layout, container, false);
btnDayStart = (Button) myView.findViewById(R.id.button_daystart);
btnDayEnd = (Button) myView.findViewById(R.id.button_dayend);
textView = (TextView) myView.findViewById(R.id.textView12);
btnDayStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
FragmentTransaction ft = ((FragmentActivity)getActivity()).getSupportFragmentManager().beginTransaction();
datePicker.show(ft, "datepicker");
}
});
btnDayEnd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//showDialog();
}
});
return myView;
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.MONTH, month);
c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
String currentDateString = DateFormat.getDateInstance(DateFormat.FULL).format(c.getTime());
textView.setText(currentDateString);
}
}
DatePickerDialog Fragment:
package at.marcelklein.drautaxi;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import java.util.Calendar;
public class DatePickerFragment extends DialogFragment {
DatePickerDialog.OnDateSetListener onDateSet;
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
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(getActivity(), onDateSet, year, month, day);
}
}
Thanks in advance!

You forgot to assign your fragment as a listener. Add it as listener like this
btnDayStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.onDateSet = FourthFragment.this
FragmentTransaction ft = ((FragmentActivity)getActivity()).getSupportFragmentManager().beginTransaction();
datePicker.show(ft, "datepicker");
}
});

I changed my code to this: DatePickerDialog
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
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(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int year, int month, int day) {
TextView tv = (TextView) getActivity().findViewById(R.id.textView12);
DecimalFormat df = new DecimalFormat("00");
tv.setText("Gewähltes Datum:");
tv.setText(tv.getText() + "\nJahr: " + year);
tv.setText(tv.getText() + "\nMonat: " + df.format(month));
tv.setText(tv.getText() + "\nTag: " + df.format(day));
}
----------- And my Fragment where i call the DatePickerDialog:
public class FourthFragment extends Fragment {
View myView;
public TextView textView;
Button btnDayStart, btnDayEnd;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fourth_layout, container, false);
btnDayStart = (Button) myView.findViewById(R.id.button_daystart);
btnDayEnd = (Button) myView.findViewById(R.id.button_dayend);
textView = (TextView) myView.findViewById(R.id.textView12);
btnDayStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment datePicker = new DatePickerFragment();
datePicker.show(getFragmentManager(), "date Picker");
}
});
return myView;
}
Now i change the TextView directly from the DatePickerDialog.
I think thats not the best Solution...
The think i want is a Range Date Picker like "TimeSquare DatePicker".
But i cant choose days from the past in "TimeSquare DatePicker".
Any suggestions?

Related

How do I call my Date Picker from a button press?

I am trying to create an app that allows me to pick a date and a table is populated with appointments on that day. I am having troubles with getting the date picker to show.
I have taken a look at this https://developer.android.com/guide/topics/ui/controls/pickers and created a date picker from this code. I want to call that date picker from a button press found in the AddAppointmentActivity class.
Here is my Appointment class:
package com.example.dentdevils.ui.HomeLinks;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.DialogFragment;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.TextView;
import com.example.dentdevils.R;
import com.example.dentdevils.ui.HomeActivity;
import java.util.Calendar;
public class AddAppointmentActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_appointment);
// Date label
TextView dateLabel = (TextView) findViewById(R.id.txtDateLabel);
// Date Picker Button Functionality
Button datePicker = (Button) findViewById(R.id.btnDatePicker);
datePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
// Back Button Functionality
Button btnBack = (Button) findViewById(R.id.btnBack);
btnBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent launchHomepage = new Intent(AddAppointmentActivity.this, HomeActivity.class);
startActivity(launchHomepage);
}
});
}
}
class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
#NonNull
#Override
public Dialog onCreateDialog(#Nullable Bundle savedInstanceState) {
final Calendar calendar = Calendar.getInstance();
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
return new DatePickerDialog(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
// Get date set by user and display appointments in table for the date chosen.
}
public void showDatePickerDialog() {
DialogFragment newFragment = new com.example.dentdevils.ui.HomeLinks.DatePickerFragment();
newFragment.show(getFragmentManager(), "datePicker");
}
}
I did have the classes in separate files but was testing different things hence why they are in the same file (I will move them back out again to separate files after I have managed to call the date picker).
My question is, how would I call the date picker dialog from the button press?
datePicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
});
You don't need create an extra dialog fragment for date picker. Just create DatePickerDialog object and call show().
Example:
val calendar = Calendar.getInstance()
val dialog = DatePickerDialog(context,
DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->
// TODO
}, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_WEEK_IN_MONTH))
dialog.show()

Data exchange via Intent between Fragments works on pre-5.0 but not on Android 5.0

As a part of The Big Nerd Ranch's Android Guide example Criminal Intent,
I am updating a button with date/time entered in the
Date/TimePicker. Button and Date/TimePicker reside in different
fragments. I am transferring data between them using an Intent. It
works fine on Pre-Lollipop devices but doesn't seem to update button
text on Android 5.0 or Lollipop devices. What am I missing?
Full code can be seen at Github.
CrimeFragment.java
package com.sudhirkhanger.android.criminalintent;
import java.util.Date;
import java.util.UUID;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
public class CrimeFragment extends Fragment {
private Crime mCrime;
private EditText mTitleField;
private Button mDateButton;
private Button mTimeButton;
private CheckBox mSolvedCheckBox;
private static final String TAG = "CriminalFragment";
public static final String EXTRA_CRIME_ID = "com.sudhirkhanger.android.criminalintent.crime_id";
private static final String DIALOG_DATE = "date";
private static final String DIALOG_TIME = "time";
private static final int REQUEST_DATE = 0;
private static final int REQUEST_TIME = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID crimeId = (UUID) getArguments().getSerializable(EXTRA_CRIME_ID);
mCrime = CrimeLab.get(getActivity()).getCrime(crimeId);
}
private void updateDateAndTime() {
Date d = mCrime.getDate();
CharSequence c = DateFormat.format("EEEE, MMM dd, yyyy", d);
CharSequence t = DateFormat.format("h:mm a", d);
mDateButton.setText(c);
mTimeButton.setText(t);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_crime, parent, false);
mTitleField = (EditText) v.findViewById(R.id.crime_title);
mTitleField.setText(mCrime.getTitle());
mTitleField.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence c, int start, int before,
int count) {
mCrime.setTitle(c.toString());
}
public void beforeTextChanged(CharSequence c, int start, int count,
int after) {
// This space intentionally left blank
}
public void afterTextChanged(Editable c) {
// This one too
}
});
mDateButton = (Button) v.findViewById(R.id.crime_date);
mDateButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getSupportFragmentManager();
DatePickerFragment dialog = DatePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
dialog.show(fm, DIALOG_DATE);
}
});
mTimeButton = (Button) v.findViewById(R.id.crime_time);
mTimeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
FragmentManager fm = getActivity().getSupportFragmentManager();
TimePickerFragment dialog = TimePickerFragment
.newInstance(mCrime.getDate());
dialog.setTargetFragment(CrimeFragment.this, REQUEST_TIME);
dialog.show(fm, DIALOG_TIME);
}
});
updateDateAndTime();
mSolvedCheckBox = (CheckBox) v.findViewById(R.id.crime_solved);
mSolvedCheckBox.setChecked(mCrime.isSolved());
mSolvedCheckBox
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// Set the crime's solved property
mCrime.setSolved(isChecked);
}
});
return v;
}
public static CrimeFragment newInstance(UUID crimeId) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_CRIME_ID, crimeId);
CrimeFragment fragment = new CrimeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_OK)
return;
if (requestCode == REQUEST_DATE) {
Date date = (Date) data
.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
mCrime.setDate(date);
updateDateAndTime();
} else if (requestCode == REQUEST_TIME) {
Date date = (Date) data
.getSerializableExtra(TimePickerFragment.EXTRA_TIME);
mCrime.setDate(date);
updateDateAndTime();
}
}
}
DatePickerFragment.java
package com.sudhirkhanger.android.criminalintent;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.View;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
public class DatePickerFragment extends DialogFragment {
public static final String EXTRA_DATE = "com.sudhirkhanger.android.criminalintent.date";
private Date mDate;
public static DatePickerFragment newInstance(Date date) {
Bundle args = new Bundle();
args.putSerializable(EXTRA_DATE, date);
DatePickerFragment fragment = new DatePickerFragment();
fragment.setArguments(args);
return fragment;
}
private void sendResult(int resultCode) {
if (getTargetFragment() == null)
return;
Intent i = new Intent();
i.putExtra(EXTRA_DATE, mDate);
getTargetFragment().onActivityResult(getTargetRequestCode(),
resultCode, i);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mDate = (Date) getArguments().getSerializable(EXTRA_DATE);
// Create a Calendar to get the year, month, and day
final Calendar calendar = Calendar.getInstance();
// calendar.setTime(mDate);
int year = calendar.get(Calendar.YEAR);
int month = calendar.get(Calendar.MONTH);
int day = calendar.get(Calendar.DAY_OF_MONTH);
View v = getActivity().getLayoutInflater().inflate(
R.layout.dialog_date, null);
DatePicker datePicker = (DatePicker) v
.findViewById(R.id.dialog_date_datePicker);
datePicker.init(year, month, day, new OnDateChangedListener() {
public void onDateChanged(DatePicker view, int year, int month,
int day) {
// Translate year, month, day into a Date object using a
// calendar
int hour = calendar.get(Calendar.HOUR_OF_DAY);
int minute = calendar.get(Calendar.MINUTE);
mDate = new GregorianCalendar(year, month, day, hour, minute)
.getTime();
// Update argument to preserve selected value on rotation
getArguments().putSerializable(EXTRA_DATE, mDate);
}
});
return new AlertDialog.Builder(getActivity())
.setView(v)
.setTitle(R.string.date_picker_title)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
sendResult(Activity.RESULT_OK);
}
}).create();
}
}
The problem isn't with the communication between the Fragments, it's that for some reason the default CalendarView DatePicker in Lollipop never calls the OnDateChanged() method, so mDate in DatePickerFragment.java never gets changed; DatePickerFragment sends back to CrimeFragment the same value it received from CrimeFragment, so it only looks like the communication between the two Fragments isn't working.
The Lollipop DatePicker does call OnDateChanged() when it's in SpinnerView mode, so CrimeFragment's date will then get properly updated. Unfortunately, Lollipop ignores the android:calendarViewShown="false" directive in the DatePicker's tag in the dialog_date.xml file. The only way to force the DatePicker to display as spinners is to include a android:datePickerMode="spinner" directive in the DatePicker's xml tag. You will get a warning that this directive is supported in API 21 only, but it will be ignored by devices running pre-5.0 Android.You have to keep the calendarViewShown="false" directive for pre-5.0 devices.
DatePickerDialog appears to have been fixed in Android 5.0, so you could also use that resource in DatePickerFragment to make things work.

Android DatePicker and Button issues

I'm trying to have a DatePicker dialog display when a user clicks on a button that says "Set your birthday", and what I need then is for the button to then display the user's selection back in the button. I have tried some of the solutions listed on this site with a TextView, but all to no avail. The DatePicker is displaying just fine, but I can't get the data to show up on the Button. I've tried these solutions: DatePicker not updating Textview in Android Display datepickers value in a textview Android: DatePicker and DatePicker Dialog How to transfer the formatted date string from my DatePickerFragment?
Here's my code:
First the DatePickerFragment:
public class DatePickerFragment extends DialogFragment implements DatePickerDialog.OnDateSetListener {
TheListener listener;
public interface TheListener {
public void returnDate(String date);
}
#Override
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(getActivity(), this, year, month, day);
}
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar c = Calendar.getInstance();
c.set(year, monthOfYear, dayOfMonth);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String formattedDate = sdf.format(c.getTime());
if (listener != null) {
listener.returnDate(formattedDate);
}
}
}
Now, the Fragment that is calling it:
public class SignUpFragment extends Fragment implements MyBirthday.TheListener {
private Button btnBirthday;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_signup, container, false);
return view;
}
#Override
public void onResume() {
super.onResume();
btnBirthday = (Button) getActivity().findViewById(R.id.signup_birthday_button);
btnBirthday.setText("Set your birthday");
btnBirthday.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DialogFragment picker = new DatePickerFragment();
picker.show(getFragmentManager(), "datePicker");
}
});
}
#Override
public void returnDate(String date) {
btnBirthday.setText(date);
}
}
Any and all help will be greatly appreciated. If this is a duplicate question, I'm sorry for that, but I couldn't find a way to get my program to behave in the way I would like for it to. I couldn't find a solution on here.
Thanks in advance.
Try this. This will show you how to render the information in a textview, but you can transfer that to a button as well. You can find the full source code on http://www.ahotbrew.com/android-datepicker-example/
package com.ahotbrew.datepicker;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.DatePicker;
import android.widget.TextView;
import java.util.Calendar;
public class MainActivity extends ActionBarActivity {
public static TextView SelectedDateView;
public static class DatePickerFragment 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) {
SelectedDateView.setText("Selected Date: " + (month + 1) + "-" + day + "-" + year);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SelectedDateView = (TextView) findViewById(R.id.selected_date);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
}

Getting data from a DatePickerDialog to a fragment

As above I am trying to work out how to pass back the date selected by the user. I have worked out how to get the date selected by using the onDateSet method but I do not know how to feed this back to the parent fragment, and then set the EditText text to the date selected.
package com.example.androidvehicle;
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
public class fragmentServicing extends Fragment {
callBack mCallBack;
Button mot;
Button servicing;
Button tax;
EditText txtService;
final int Date_Dialog_ID=0;
int cDay,cMonth,cYear; // this is the instances of the current date
Calendar cDate;
int sDay,sMonth,sYear; // this is the instances of the entered date
int id_dialog = 1;
int yr, day, month = 0;
// interfacing back to activity
public interface callBack
{
public void onItemSelected(String id);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_servicing, container, false);
txtService = (EditText) view.findViewById(R.id.txtServiceDate);
mot = (Button) view.findViewById(R.id.buttonMOT);
servicing = (Button) view.findViewById(R.id.buttonService);
servicing.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// this will then pass back to the activity the string hello
mCallBack.onItemSelected("hello");
getActivity().showDialog(1);
}
});
mot.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
getActivity().showDialog(1);
}
});
return view;
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallBack = (callBack) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
// this is an override for when the dialog is created
protected Dialog onCreateDialog(int id)
{
switch(id)
{
// this will return a date picker dialog if 1 is passed
// could use another number for another dialog
case 1:
// passes it the current date
return new DatePickerDialog(getActivity(), mDateSetListener, yr, month, day);
}
return null;
}
// this returns the date back that has been selected by the user
private DatePickerDialog.OnDateSetListener mDateSetListener =
new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
yr = year;
month = monthOfYear;
day = dayOfMonth;
Log.d("date selected", "year "+ yr+ " month " +month+" day "+day);
}
};
}
You can set DateListner on Edittext onClicklistner..
import java.util.Calendar;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
public class DateListener implements OnClickListener, OnDateSetListener {
private Activity activity;
private int year;
private int monthOfYear;
private int dayOfMonth;
private View touchedView;
public DateListener(Activity activity) {
this.activity = activity;
final Calendar c = Calendar.getInstance();
this.year = c.get(Calendar.YEAR);
this.monthOfYear = c.get(Calendar.MONTH);
this.dayOfMonth = c.get(Calendar.DAY_OF_MONTH);
}
public int getYear() {
return year;
}
public int getMonth() {
return monthOfYear;
}
public int getDay() {
return dayOfMonth;
}
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
this.year = year;
this.monthOfYear = monthOfYear + 1;
this.dayOfMonth = dayOfMonth;
updateDisplay();
updateEditText();
}
#Override
public void onClick(View v) {
touchedView = v;
new DatePickerDialog(activity,
this, this.getYear(), this.getMonth(), this.getDay()).show();
}
private void updateDisplay() {
((TextView) touchedView).setText(
new StringBuilder()
.append(pad(dayOfMonth)).append(".")
.append(pad(monthOfYear)).append(".")
.append(pad(year)));
}
private void updateEditText() {
((EditText) touchedView).setText(
new StringBuilder()
.append(pad(dayOfMonth)).append(".")
.append(pad(monthOfYear)).append(".")
.append(pad(year)));
}
private static String pad(int c) {
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
}
In Your Fragment
DateListener dateListener = new DateListener(getActivity());
edittext.setOnClickListener(dateListener);

TimePickerDialog is not displaying / showing

I have a TimePickerDialog that I would like to show the user when she pushes on a button, so that she can choose a time to set the display to (some time other than the current time). Currently when the button is pushed the current time is displayed in a TextView and a Toast. Also the screen Darkens and a small box in the center of screen appears. The TimePickerDialog does not display to the user.
Here's the code;
import java.util.Calendar;
import android.os.Bundle;
import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class AddAlarmActivity extends FragmentActivity implements TimePickerDialog.OnTimeSetListener, TimePickerDialog.OnDismissListener {
Button setTime;
public int hour_local;
public int minute_local;
public Dialog onCreateDialog;
public TimePicker timePicker;
public TextView displayAlarm;
static final int TIME_DIALOG_ID = 999;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_alarm);
//add a TextView thing to this part
setTime = (Button) findViewById(R.id.button_set_time);
displayAlarm = (TextView) findViewById(R.id.tvDisplayTime);
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onCreateDialog(savedInstanceState);
showTimePickerDialog(timePicker);
displayAlarm.setText(hour_local + ":" + minute_local);
}
});
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
hour_local = c.get(Calendar.HOUR_OF_DAY);
minute_local = c.get(Calendar.MINUTE);
Context context = getApplicationContext();
CharSequence text = hour_local + ":" + minute_local;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getApplicationContext(), this, hour_local, minute_local,
DateFormat.is24HourFormat(getApplicationContext()));
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new DialogFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void onDismiss(DialogInterface dialog){
System.out.println("oui c'est très bon !");
}
public void onTimeSet(TimePicker view, int hour_l, int minute_l) {
hour_local = hour_l;
minute_local = minute_l;
System.out.println("voila");
}
}
I would advice that you follow the developer sites way of doing it:
Create a static class that handles the dialog fragment
public static class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
}
}
Call this method in your button on click listener:
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
Source here.
public class AddAlarmActivity extends FragmentActivity {
Button setTime;
public static int hour_local;
public static int minute_local;
public Dialog onCreateDialog;
public TimePicker timePicker;
public static TextView displayAlarm;
public static int hour_alarm;
public static int minute_alarm;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_alarm);
setTime = (Button) findViewById(R.id.button_set_time);
displayAlarm = (TextView) findViewById(R.id.tvDisplayTime);
final Calendar c = Calendar.getInstance();
hour_local = c.get(Calendar.HOUR_OF_DAY);
minute_local = c.get(Calendar.MINUTE);
displayAlarm.setText(hour_local + ":" + minute_local);
setTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTimePickerDialog(timePicker);
}
});
}
public void onTimeSet(TimePicker view, int hour_l, int minute_l) {
// intentionally blank
}
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
/*New static class*/
public static class TimePickerFragment extends DialogFragment implements TimePickerDialog.OnTimeSetListener {
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
hour_local = c.get(Calendar.HOUR_OF_DAY);
minute_local = c.get(Calendar.MINUTE);
Context context = getActivity();
CharSequence text = hour_local + ":" + minute_local;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour_local, minute_local,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hour_l, int minute_l) {
hour_alarm = hour_l;
minute_alarm = minute_l;
displayAlarm.setText(hour_alarm + ":" + minute_alarm);
}
}
}
TimePickerDialog dialog = new TimePickerDialog(this,OnTimeSet,DateTime.Now.Hour,DateTime.Now.Minute,true);
dialog.Show();
void OnTimeSet (object sender, TimePickerDialog.TimeSetEventArgs e)
{
}

Categories

Resources