I want to set date and time in preferences.In my app i am using the custom date&time dialog and want to set the time & date in preferences choose from that dialog.
Function to display date and time picker dialog:
public void showDialog() {
// TODO Auto-generated method stub
Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.date_time_dialog);
dialog.setTitle("Custom Dialog");
set_time = (Button) dialog.findViewById(R.id.set_time);
dialog.show();
timepk = (TimePicker)dialog.findViewById(R.id.timePicker1);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
min = c.get(Calendar.MINUTE);
timepk.setOnTimeChangedListener(new TimePicker.OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
hour = hourOfDay;
min = minute;
}
});
datepk = (DatePicker)dialog.findViewById(R.id.datePicker1);
final Calendar cal = Calendar.getInstance();
Year = cal.get(Calendar.YEAR);
month = cal.get(Calendar.MONTH);
day = cal.get(Calendar.DAY_OF_MONTH);
datepk.init(Year, month, day, new OnDateChangedListener() {
@Override
public void onDateChanged(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
Year = year;
month = monthOfYear;
day = dayOfMonth;
}
});
Function to save date and time in shared preferences:
public void setTime(){
SharedPreferences prefer = getSharedPreferences("MyPREFERENCES", 0);
SharedPreferences.Editor preferencesEditor = prefer.edit();
preferencesEditor.putInt("Year",Year);
preferencesEditor.putInt("Month",month);
preferencesEditor.putInt("Day",day);
preferencesEditor.putInt("Hour",hour);
preferencesEditor.putInt("Min",min);
Boolean flag = preferencesEditor.commit();
if(flag==true)
{
Toast.makeText(getApplicationContext(),
"Time saved sucessfully!",
Toast.LENGTH_LONG).show();
}
}