Good day!
I have a Dialog class that contains TimePicker. TimePicker is set for 24hour mode. When i pick time with hour < 12 - Picker returns it with +12 hours more.
For example -
i've set 07:25 - returns 19:25. And vise-versa
if i set 19:43 - returns 07:42. And
if i set 12:01, for example - TimePicker returns idiotic 24:01.
What's problem with this tool?
Here the full code of my Dialog class:
public class TimePickerDialog extends DialogFragment {
public static final String EXTRA_TIME = "time";
#Bind(R.id.pickerTime_timePicker) TimePicker timePicker;
//// DialogFragment methods
#Override #NonNull
public Dialog onCreateDialog(Bundle savedInstanceState) {
View view = getActivity().getLayoutInflater().inflate(R.layout.picker_time, null);
ButterKnife.bind(this, view);
timePicker.setIs24HourView(true);
return new AlertDialog.Builder(getActivity())
.setView(view)
.setTitle(getString(R.string.time_picker_dialog_label))
.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
sendResult(Activity.RESULT_OK);
}
})
.setNegativeButton(android.R.string.cancel, null)
.create();
}
//// Private methods
private void sendResult(int resultCode) {
if (getTargetFragment() == null) {
return;
}
Intent intent = new Intent();
intent.putExtra(EXTRA_TIME, getTimeFromTimePicker(timePicker));
getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
}
private Date getTimeFromTimePicker(TimePicker timePicker) {
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, timePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker.getCurrentMinute());
return calendar.getTime();
}
}
Put this line,
timePicker.setCurrentHour(Calendar.getInstance().get(Calendar.HOUR_OF_DAY));
below,
timePicker.setIs24HourView(true);
which will set the current time corretly.
Let me know if it works for you...
I guess, you should use calendar.set(Calendar.HOUR_OF_DAY, timePicker.getCurrentHour());
Just read the documentation
The provided example works for everyone, no need to bind something. Why do you need that extra logic inside the dialog? It should be responsible for picking the time. The other logic should be in your controller.
Related
I am opening timepicker in dialogfragment in my fragment class.
var dialog = new TimePickerDialogFragment(_activity, DateTime.Now, new OnTimeSetListener());
dialog.Cancelable = false;
dialog.Show(_fg, null);
Here TimePickerDialogFragment extends DialogFragment.
public class TimePickerDialogFragment : DialogFragment
{
private Activity _activity;
private DateTime _date;
private readonly TimePickerDialog.IOnTimeSetListener _listener;
public TimePickerDialogFragment(Activity activity, DateTime date, TimePickerDialog.IOnTimeSetListener listener)
{
_activity = activity;
_date = date;
_listener = listener;
}
public override Dialog OnCreateDialog(Bundle savedState)
{
var dialog = new TimePickerDialog(_activity, _listener, _date.Hour, _date.Minute, true);
dialog.SetTitle("Enter Time"+ DateTime.Now.ToString());
return dialog;
}
}
Here is my listener class
public class OnTimeSetListener : Java.Lang.Object, TimePickerDialog.IOnTimeSetListener
{
public void OnTimeSet(TimePicker view, int hourOfDay, int minute)
{
}
}
Now I want to update the title as soon as user selects a new time while the pop up is opened. The OnTimeSet is called when I click on set button on popup.I don't want to update there. How can I achieve this?
Is there any other way to open timepicker dialog apart from this that I can try?
I am new to android. Any help is appreciated.
In order to get notified when time is changed you need to create a subclass of TimePickerDialog and override OnTimeChanged method which is called when user changes time in the picker. Add a TimeChanged event in the new subclass and trigger it from the overridden method. In the event handler you will be able to set the dialog title based on the new time.
I've a Listview with two linear layouts and there is one button add new row . When i click add new row button i want to create new row of buttons dynamically. After that click on that created button i want to show an time picker dialog . When user click set time button i want to set that time in that button. My problem is All the buttons(with different id) are added fine and when click that button time picker dialog was pop up. But after click set time button the time will not set . How can i add this time to the button. How can i handle this button ?
It is my piece of code inside of listview onscroll listener
final LinearLayout l1 = LinearLayout) List_Layout.getChildAt(0);
LinearLayout l12 = (LinearLayout) List_Layout.getChildAt(1);
final Button button = new Button(getApplicationContext());
final Button button1 = new Button(getApplicationContext());
add_button.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
button.setLayoutParams(lparams);
button1.setLayoutParams(lparams);
button.setId(0);
button1.setId(1);
l1.addView(button, lparams);
l12.addView(button1, lparams);
}
}
button.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("deprecation")
public void onClick(View v)
{
showDialog(TIME_DIALOG_ID);
}
}
button1.setOnClickListener(new OnClickListener()
{
#SuppressWarnings("deprecation")
public void onClick(View v)
{
// TODO Auto-generated method stub
Log.e("tag 1", button1.getTag()+"");
showDialog(TIME_DIALOG_ID);
}
});
Rest of the codes for timepicker dialog is works fine
It's just sample code
Please anyone help me get out from this riddle.
Edit:
static final int TIME_DIALOG_ID = 998;
private int hour;
private int minute;
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minute = selectedMinute;
}
}
You need to set text of button or button1 to the time that was actually picked by the user. To do so, code some button.setText(<formatted time>) in the timePickerListener.
Here's some line of code, I use to format date and time from a java.util.Date object:
Date date = new Date();
java.text.DateFormat dateFormat = DateFormat.getMediumDateFormat(context);
java.text.DateFormat timeFormat = DateFormat.getTimeFormat(context);
button.setText(String.format("%s %s", dateFormat.format(date), timeFormat.format(date)));
In your case of the time picker you can just format the selected values into a string:
button.setText(String.format("%02d:%02d", selectedHour, selectedMinute));
I have 2 datepickers and 2 timepickers on a screen and also a submit button. The user selects the start date, start time, end date, and end time. The program then takes these values and stores them into variables, however the variables only return the default values for these controls. Is there anyway to get the updated value from each of these controls?
My code looks like this for the edit screen:
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.editscreen);
timepickerStart = (TimePicker)findViewById(R.id.timePicker1);
timepickerEnd = (TimePicker)findViewById(R.id.timePicker2);
datepickerStart = (DatePicker)findViewById(R.id.datePicker1);
datepickerEnd = (DatePicker)findViewById(R.id.datePicker2);
submitbutton = (Button)findViewById(R.id.submit);
locationText = (EditText)findViewById(R.id.locationText);
eventText = (EditText)findViewById(R.id.eventText);
}
public void DateStart(View v)
{
GlobalVariables.datepickerYearStart = datepickerStart.getYear();
GlobalVariables.datepickerMonthStart = datepickerStart.getMonth();
GlobalVariables.datepickerDayStart = datepickerStart.getDayOfMonth();
}
public void DateEnd(View v)
{
GlobalVariables.datepickerYearEnd = datepickerEnd.getYear();
GlobalVariables.datepickerMonthEnd = datepickerEnd.getMonth();
GlobalVariables.datepickerDayEnd = datepickerEnd.getDayOfMonth();
}
public void TimeStart(View v)
{
GlobalVariables.timepickerHourStart = timepickerStart.getCurrentHour();
GlobalVariables.timepickerMinuteStart = timepickerStart.getCurrentMinute();
}
public void TimeEnd(View v)
{
GlobalVariables.timepickerHourEnd = timepickerEnd.getCurrentHour();
GlobalVariables.timepickerMinuteEnd = timepickerEnd.getCurrentMinute();
}
public void submitClicked(View v)
{
startActivity(new Intent(this, AddToCalendar.class));
}
Rewrite
Looking at your current code, let's stick with the various get methods from DatePicker and TimePicker. However you never call DateStart() or any of the others, they look like you have them set up for an OnClickListener... Regardless, try this:
public void submitClick(View v) {
DateStart(null);
TimeStart(null);
DateEnd(null);
TimeEnd(null);
// Do what you please your GlobalVariables
}
Though I might leave out the multiple GlobalVariables and store one long value for each date/time:
public void submitClick(View v) {
Calendar calendar = Calendar.getInstance();
calendar.set(datepickerStart.getYear(), datepickerStart.getMonth(),
datepickerStart.getDayOfMonth(), timepickerStart.getCurrentHour(),
timepickerStart.getCurrentMinute(), 0);
long startTime = calendar.getTimeInMillis();
// And similar approach for the end time, then use them however you please
}
You need to set a listener to your DatePicker:
DatePicker picker = new DatePicker(this);
picker.init(<year>, <monthOfYear>, <dayOfMonth>, new DatePicker.OnDateChangedListener() {
#Override
public void onDateChanged(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
//set the value of the variable here
}
});
TimePicker Dialog retrieves onCreate time, not current time if activity remains open it wont change ... I am wanting the dialog to always show current time not just when the activity started. i am currently using the following in the onCreate:
final Calendar onscene = Calendar.getInstance();
buildingfireonsceneHour = onscene.get(Calendar.HOUR_OF_DAY);
buildingfireonsceneMinute = onscene.get(Calendar.MINUTE);
Pass the updateTimer() function the current time just before you open the dialog, for example:
mTimePickerDialog = new TimePickerDialog(this, null, 0, 0, false);
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Calendar calendar = Calendar.getInstance();
mTimePickerDialog.updateTime(calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE));
mTimePickerDialog.show();
}
});
** Addition **
I believe you want to override the onPrepareDialog() function like this:
#Override
protected void onPrepareDialog (int id, Dialog dialog, Bundle args) {
super.onPrepareDialog(id, dialog, args);
if(id != DATE_DIALOG_ID) {
final Calendar c = Calendar.getInstance();
((TimePickerDialog) dialog).updateTime(c.get(Calendar.HOUR_OF_DAY), c.get(Calendar.MINUTE));
}
}
The app has initial message screen that is displayed the first time it run where a date is obtained from user using datepicker then from next time it goes directly to main.xml. This is the logic i tried
in onCreate()
if(<date set>)
{
<open main.xml>
<listeners>
}
else
{
<get date from user>
<set flag>
setContentView(R.layout.initial_msg);
<make changes in main.xml according to date>
}
The problem is the first time it executes it obtains the date but the listeners are not loaded, i think this is because the code is not executed at all. when i place the listener outside the if block i get a null pointer exception. But when i close the app and start it again it works as this time it opens if() block not else().
public class pgactivity extends Activity
{
/** Called when the activity is first created. */
SharedPreferences prefs;
Calendar c=Calendar.getInstance();
Calendar tempDate;
TextView tv1,tv2;
Menu theMenu;
LayoutInflater li;
int week;
DatePickerDialog.OnDateSetListener d=new DatePickerDialog.OnDateSetListener()
{
//#override
public void onDateSet(DatePicker view, int year, int monthOfYear,int dayOfMonth)
{
c.set(Calendar.DATE,dayOfMonth);
c.set(Calendar.MONTH,monthOfYear);
c.set(Calendar.YEAR,year);
if(checkValidity())
{
SharedPreferences.Editor editor=prefs.edit();
//set the flag that indicates concieved_date has been added
editor.putBoolean("concieved_date", true);
int datepref;
datepref=c.get(Calendar.DATE);
datepref=datepref*1000000;
datepref+=c.get(Calendar.MONTH)*10000;
datepref+=c.get(Calendar.YEAR);
editor.putInt("date",datepref);
editor.commit();
setContentView(R.layout.main);
setData();
}
}
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
//check if concieved date is set from the prefs file "app_data"
//if yes open application page else open initial message screen to set the date
prefs=getApplicationContext().getSharedPreferences("app_data",Context.MODE_APPEND);
if(prefs.getBoolean("concieved_date", false))
{
setContentView(R.layout.main);
setData();
//Listener for the temp button 'false'
//It resets the flag used to indicate if date is set or not. used for testing purpose
Button btn1=(Button)findViewById(R.id.setfalse);
btn1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("concieved_date", false);
editor.commit();
TextView tv3=(TextView)findViewById(R.id.test);
tv3.setText("entered listener");
}
});
//Listener for the weekly_tip text view
//when clicked open the layout giving the full description
TextView tv2=(TextView)findViewById(R.id.weekly_tip);
tv2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent j=new Intent(pgactivity.this,weekly.class);
Bundle b=new Bundle();
b.putInt("cur_week",week);
j.putExtras(b);
startActivity(j);
}
});
//Listener for open_remainders button to switch to Remainders page
Button btn2=(Button)findViewById(R.id.open_remainders);
btn2.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Intent i=new Intent(pgactivity.this,RemaindersPage.class);
startActivity(i);
}
});
}
else
{
setContentView(R.layout.initial_msg);
//click listener for textview 2
TextView tv1=(TextView)findViewById(R.id.init_msg);
tv1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
SharedPreferences.Editor editor=prefs.edit();
editor.putBoolean("concieved_date", true);
editor.commit();
new DatePickerDialog(pgactivity.this,d,
c.get(Calendar.YEAR),
c.get(Calendar.MONTH),
c.get(Calendar.DAY_OF_MONTH)).show();
}
});
}
}
void setData()
{
Long sec,tempSec;
int date,day,month,year;
date=prefs.getInt("date", 10101010);
day=date/1000000;
date=date%1000000;
month=date/10000;
date=date%10000;
year=date;
c.set(year, month, day);
tempDate=c;
//insert value to concieved_date textfield
tv1=(TextView)findViewById(R.id.concieved_date);
tv1.setText(android.text.format.DateFormat.format("dd MMM yyyy", tempDate));
//insert value to delivery_date
tv1=(TextView)findViewById(R.id.delivery_date);
tempDate.add(Calendar.DATE, 280);
tv1.setText(android.text.format.DateFormat.format("dd MMM yyyy", tempDate));
//insert value to days_to_delivery
tv1=(TextView)findViewById(R.id.days_to_delivery);
c=Calendar.getInstance(); //c has current date
sec=tempDate.getTimeInMillis()-c.getTimeInMillis(); //find diff in millisecs
sec=sec/86400000;
tv1.setText(sec.toString());
//insert value for days_into_pregnancy
tv1=(TextView)findViewById(R.id.days_into_pregnancy);
tempSec=280-sec;
tv1.setText(tempSec.toString());
//insert value for current_week
tv1=(TextView)findViewById(R.id.current_week);
tempSec=tempSec/7;
week=tempSec.intValue();
tv1.setText(tempSec.toString());
}
//user method to check the date validity : check if date entered is a reasonable value
boolean checkValidity()
{
Long duration;
tempDate=Calendar.getInstance(); //get today's date in c
//check if user date is on or before today's date
if(tempDate.before(c))
{
AlertDialog.Builder ad=new AlertDialog.Builder(this);
ad.setMessage("Specified date should be on or before today's date");
ad.setNeutralButton("OK",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0,int arg1){}
}
);
ad.show();
return false;
}
//check if diff between user date and todays date is more than 280 days
duration=tempDate.getTimeInMillis()-c.getTimeInMillis();
duration/=86400000;
if(duration>280)
{
AlertDialog.Builder ad=new AlertDialog.Builder(this);
ad.setMessage("Specified date can be atmost 280 days before today's date");
ad.setNeutralButton("OK",new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0,int arg1){}
}
).show();
return false;
}
return true;
}
}
If you need your listeners in the else-block, too, you can put this code before the if-block.
If the layout changes if the if or the else is executed, you can use the onClick-attribute in your XML-Layout definition.
To save your data, you can use SharedPreferences.