How to set previous selected value in TimePicker?
I mean, click on TextView, TimePicker dialog occurs, then I select the time and set it in the TextView, e.g. 12:30 PM on TextView.
After that, if I want to change the time, click again to TextView and then TimePicker dialog should show the previous selected value. So the TimePicker should display 12:30 PM.
How can I do that?
If you create Time Picker Dialog with onCreateDialog and call it it will automatically store the previous value.
#Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case 0:
TimePickerDialog timeDlg = new TimePickerDialog(this,
new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay,
int minute) {
// TODO Auto-generated method stub
if (hourOfDay > 12) {
hourOfDay = hourOfDay - 12;
time = " PM";
} else if (hourOfDay < 12 && hourOfDay != 0) {
time = " AM";
} else if (hourOfDay == 12) {
time = " PM";
} else if (hourOfDay == 0) {
hourOfDay = 12;
time = " AM";
}
Toast.makeText(
getApplicationContext(),
new StringBuilder().append(pad(hourOfDay))
.append(":").append(pad(minute))
.append(time), Toast.LENGTH_SHORT)
.show();
}
}, 12, 00, false);
timeDlg.setMessage("Set Time:");
timeDlg.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Dismiss",
Toast.LENGTH_SHORT).show();
}
});
return timeDlg;
}
return null;
}
Use showDialog(id); to Show the Dialog.
Related
I found some problem for TimePicker widget. After user change time in widget setHour and setMinute methods not works.
public class MainActivity extends AppCompatActivity {
private Button mButton;
private TimePicker mTimePicker;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mButton = (Button) findViewById(R.id.reset);
mTimePicker = (TimePicker) findViewById(R.id.timePicker);
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
mTimePicker.setHour(hour);
mTimePicker.setMinute(minute);
Log.v(TAG, "onClick: " + hour + "=>" + mTimePicker.getHour());
Log.v(TAG, "onClick: " + minute + "=>" + mTimePicker.getMinute());
}
});
}
}
Step for reproduce:
Run app (my time: 13:21)
Change time on the Widget (21:21)
Tap on the Reset button
Result:time not reset to 13:21
Log:
03-30 13:18:05.765 30923-30923/ru.neverdark.timepickerproblem
V/MainActivity: onClick: 13=>21 03-30 13:18:05.765
30923-30923/ru.neverdark.timepickerproblem V/MainActivity: onClick:
18=>18
Any workaround for this problem?
Same bug I found in Issue Tracker: https://code.google.com/p/android/issues/detail?id=208180 but in SDK25 not fixed...
Demo project on the github: https://github.com/yankovskiy/TimePickerProblem
Well, I have to admit, this is not my proudest code.
But as a workaround you can have this:
mButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Calendar cal = Calendar.getInstance();
int currentHour = cal.get(Calendar.HOUR_OF_DAY);
int currentMinute = cal.get(Calendar.MINUTE);
fixValues();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
mTimePicker.setHour(currentHour);
mTimePicker.setMinute(currentMinute);
} else {
mTimePicker.setCurrentHour(currentHour);
mTimePicker.setCurrentMinute(currentMinute);
}
}
});
private void fixValues() {
// bug is not reproducible in APIs 24 and above
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) return;
try {
int hour, minute;
if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
hour = mTimePicker.getHour();
minute = mTimePicker.getMinute();
} else {
hour = mTimePicker.getCurrentHour();
minute = mTimePicker.getCurrentMinute();
}
Field mDelegateField = mTimePicker.getClass().getDeclaredField("mDelegate");
mDelegateField.setAccessible(true);
Class<?> clazz;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1) {
clazz = Class.forName("android.widget.TimePickerClockDelegate");
} else {
clazz = Class.forName("android.widget.TimePickerSpinnerDelegate");
}
Field mInitialHourOfDayField = clazz.getDeclaredField("mInitialHourOfDay");
Field mInitialMinuteField = clazz.getDeclaredField("mInitialMinute");
mInitialHourOfDayField.setAccessible(true);
mInitialMinuteField.setAccessible(true);
mInitialHourOfDayField.setInt(mDelegateField.get(mTimePicker), hour);
mInitialMinuteField.setInt(mDelegateField.get(mTimePicker), minute);
} catch (NoSuchFieldException | IllegalAccessException | ClassNotFoundException e) {
e.printStackTrace();
}
}
Tested on APIs 21, 22 and 23.
Bug is not reproducible in APIs 24, 25.
protected Dialog onCreateDialog(int id) {
checkMark = (Button) findViewById(R.id.button13) ;
checkMark.setVisibility(View.VISIBLE) ;
switch (id) {
case TIME_DIALOG_ID:
// set time picker as current time
return new TimePickerDialog(this,
timePickerListener, hour, minute,false);
case TIME_DIALOG_ID_ON:
// set time picker as current time
return new TimePickerDialog(this,
timePickerListenerOn, hour, minute,false);
}
return null;
}
How about this?
picker.setCurrentHour(date.getHours())
picker.setCurrentMinute(date.getMinutes())
I have two SeekBar in my application. One shows hours and the other progresses in interval of 15 minutes (0,15,30,45).
I have a initial value of time set to 10.30. Iam displaying the changed time in a TextView.
Now, if the user only increments the minute seekbar (eg 15 mins) the textView should show 10.45. (ie. 10.30 + 00:15). Similarly, if the user further increments the minute seekbar to 30 or 45 the TextView should show 11:00 and 11:15 respectively.
Currently, Everything works fine until the minutes goes upto 15 minutes. But when I increase the SeekBar to 30 or 45 the TextView shows 10:60 and 10:75 instead.
Here is my code:-
int hourLimit=10, minLimit=30;
seekBarHour.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar)
{
if(progressChangedHours == 0 && progressChangedMins==0)
{
txtReachingBy.setText("Reaching by:"+" "+String.valueOf(hourLimit)+":"+String.valueOf(minLimit)+":"+today.second);
}
if(progressChangedHours==0 && mins >=60)
{
hour = 1;
}
else
{
hour = hourLimit + progressChangedHours;
}
timeString = String.valueOf(hour)+":"+String.valueOf(mins)+":"+today.second;
txtReachingBy.setText("Reaching by:"+" "+timeString);
}
});
seekBarMins.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
progressChangedMins = progress;
int stepSize = 15;
progressChangedMins = (progressChangedMins/stepSize)*stepSize;
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar)
{
if(progressChangedMins == 0)
{
txtReachingBy.setText("Reaching by:"+" "+String.valueOf(hourLimit)+":"+String.valueOf(30)+":"+today.second);
}
else
{
mins = minLimit +progressChangedMins;
if(progressChangedHours==0 && mins!=0)
{
hour = hourLimit;
}
else if(progressChangedHours>=0 && mins>=60)
{
hour = hour+1;
mins = mins-60;
}
timeString = String.valueOf(hour)+":"+String.valueOf(mins)+":"+today.second;
txtReachingBy.setText("Reaching by:"+" "+timeString);
}
}
});
EDIT
: I used the Date to solve a part of my problem like so:-
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date;
try
{
date = sdf.parse(initialTime);
cal= Calendar.getInstance();
cal.setTime(date);
txtReachingBy.setText("Reaching By:"+" "+ cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE));
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
seekBarMins.setOnSeekBarChangeListener(new OnSeekBarChangeListener()
{
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser)
{
progressChangedMins = progress;
int stepSize = 15;
progressChangedMins = (progressChangedMins/stepSize)*stepSize;
seekBar.setProgress(progressChangedMins);
if(progressChangedHours ==0 && progressChangedMins!=0)
{
lblLateBy.setText("Late By (Hrs):"+" " + String.valueOf(progressChangedHours) +":"+String.valueOf(progressChangedMins));
}
else
lblLateBy.setText("Late By (Hrs):"+" " + String.valueOf(progressChangedHours) +":"+String.valueOf(progressChangedMins));
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar)
{
if(progressChangedMins==0)
{
timeString = cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+today.second;
}
else
{
cal.add(Calendar.MINUTE, progressChangedMins);
timeString = cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE)+":"+today.second;
}
txtReachingBy.setText("Reaching by:"+" "+timeString);
}
});
Now everything works fine if I drag the seek bar thumb at once to a value. The progressed value gets added to the initial time. But if I drag it to a value the initial time changes with the addition, then again if I drag it further the progressed value gets added to the new time and not the initial one.
Giving me the output as:-
Drag 1-> 15 mins > Time expected 10.45 (Fine)
Drag 2-> 30 mins > Time expected 11.00 Output I get -> 10.45+00.30 = 11.15
How can I solve this?
I want to compare the current date and the date that set by user in my "cal_set" calendar, i want to accept the date if date is today date or upcoming date else show toast if date is passed.
This is my onDateSet method.
public void onDateSet(DatePicker arg0, int year, int month, int day)
{
// TODO Auto-generated method stub
cal_set.set(Calendar.DAY_OF_MONTH,day);
cal_set.set(Calendar.MONTH, month);
cal_set.set(Calendar.YEAR, year);
if(cal_set.getTime().after(cal_now.getTime))
{
tv_date.setText(new StringBuffer().append(day).append("/").append(month).append("/").append(year));
}
else
{
Toast.makeText(getApplicationContext(),"Please select upcoming date", Toast.LENGTH_LONG).show();
}
}
};
i am setting date in cal_now when user click on view that calles onDateSet method.
iv_date.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
day_now = Calendar.getInstance(Locale.getDefault()).get(Calendar.DAY_OF_MONTH);
month_now = Calendar.getInstance(Locale.getDefault()).get(Calendar.MONTH);
year_now = Calendar.getInstance(Locale.getDefault()).get(Calendar.YEAR);
cal_now = Calendar.getInstance();
showDialog(ID_DATE);
}
});
protected Dialog onCreateDialog(int id)
{
// TODO Auto-generated method stub
switch (id)
{
case ID_DATE:
return new DatePickerDialog(this, onDateSetListener, year_now, month_now, day_now);
default:
break;
}
return null;
}
any help please.
you can compare Date with compareTo(). However, in your case, you can use Calendar methods setMaxDate() and setMinDate().
You can simply use "now = new Date();" to get the actual date.
Then to test if the entered date is superior or equal to the actual date, use:
if (setdate.compareTo(now)>=0) {
// do your stuff here.
}
public static boolean CompareDates(String strDate1,String strDate2)
{
try
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = sdf.parse(strDate1);
Date date2 = sdf.parse(strDate2);
System.out.println(sdf.format(date1));
System.out.println(sdf.format(date2));
if(date1.compareTo(date2)==0)
{
return true;
}else
{
return false;
}
}
catch (Exception e)
{
e.printStackTrace();
return false;
}
}
I solved my problem finally, now i let the datepicker get date from user and than i set that date in EditText, when user clicks on submit button i just get strings from edittext and parse them into date format like this:
s_date_temp = date_format.parse(et_sdate.getText().toString());
e_date_temp = date_format.parse(et_edate.getText().toString());
After that i compare these dates like this:
if(s_date_temp.after(e_date_temp))
{
Toast toast = Toast.makeText(getApplicationContext(), "Error: The Start Date Must Occur Prior To Th End Date!", Toast.LENGTH_LONG);
toast.show();
}
I have an Intent service running that performs a do while loop.
The service is started from an activity when a button is pressed.
Problem is when I press the button again a new service is started along side the previous service from the first press.
I want the previous service to be stopped and the new service to replace it.
Essentially i want to know how to either kill services or pass data to the running thread in order to change the do while conditions. Im not sure how to handle this.
Thanks for your help.
startAlarm.setOnClickListener(new View.OnClickListener() {
int x=0;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
getActivity().startService(alarmService);
System.out.println("Service has started.");
}
});
public class AlarmService extends IntentService{
public AlarmService() {
super("Alarm run service");
// TODO Auto-generated constructor stu
}
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
int hour = intent.getExtras().getInt("hourval");
int minute = intent.getExtras().getInt("minval");
System.out.println("Hour is : " + hour + " minute is : " + minute);
int currentHour;
int currentMinute;
do{
System.out.println("in the loop");
Calendar cal = Calendar.getInstance();
currentHour = cal.get(Calendar.HOUR_OF_DAY);
currentMinute = cal.get(Calendar.MINUTE);
System.out.println(currentHour + ":" + currentMinute + "and " + hour +":" +minute);
}while(currentHour != hour || currentMinute != minute);
System.out.println("Left loop");
Intent alarmRingStart = new Intent(getApplicationContext(),AlarmRing.class);
alarmRingStart.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(alarmRingStart);
System.out.println("Alarm has gone off");
}
#Override
public void onDestroy(){
super.onDestroy();
}
}
you can first stopService, and in service.onDestroy set a flag indicating the while loop should exit. you should always check the value of that flag.
I am trying to get Date from Datepicker, my code is below
dpResult = (DatePicker) findViewById(R.id.dpResult);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Calendar current = Calendar.getInstance();
gettingDate();
}
private void gettingDate() {
// TODO Auto-generated method stub
int day = dpResult.getDayOfMonth();
int month= dpResult.getMonth();
int year = dpResult.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
formatedDate = sdf.format(new Date(year, month, day));
// You can parse the String back to Date object by calling
try {
date = sdf.parse(formatedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), ""+formatedDate, 1000).show();
}
});
my toast shows date-month correctly but in year first two digits as 39 i.e like 3913,3914 etc please help me
you have to use this format for getting perfect and right year.
dpResult.getYear()-1900;
use dpResult.getYear()-1900
int year = dpResult.getYear();
Date is deprecated, you should use Calendar instead with the following syntax
Calendar cal = Calendar.getInstance()
cal.set(dpResult.getYear(), dpResult.getMonth()-1,getDayOfMonth())