1

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();
    }
}
Poras Bhardwaj
  • 1,073
  • 1
  • 15
  • 33

2 Answers2

1

Instead of storing each part of the date as a separate preference, storing a single long may be a better alternative. The following example (also posted in this gist) is a preference that extends a DialogPreference to make a pop up asking for the time (this is time only, but you can swap the time picker out for a date picker and update the values in onDialogClosed easily enough). It also implements an OnPreferenceChangeListener so that you can do something any time you set the new preference (as an example it updates the summary to the new time set):

import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.preference.Preference;
import android.util.AttributeSet;
import android.view.View;
import android.widget.TimePicker;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;

public class TimePreference extends DialogPreference implements Preference.OnPreferenceChangeListener {
    private TimePicker picker = null;
    public final static long DEFAULT_VALUE = 0;

    public TimePreference(final Context context, final AttributeSet attrs) {
        super(context, attrs, 0);
        this.setOnPreferenceChangeListener(this);
    }

    protected void setTime(final long time) {
        persistLong(time);
        notifyDependencyChange(shouldDisableDependents());
        notifyChanged();
    }

    protected void updateSummary(final long time) {
        final DateFormat dateFormat = android.text.format.DateFormat.getTimeFormat(getContext());
        final Date date = new Date(time);
        setSummary(dateFormat.format(date.getTime()));
    }

    @Override
    protected View onCreateDialogView() {
        picker = new TimePicker(getContext());
        picker.setIs24HourView(android.text.format.DateFormat.is24HourFormat(getContext()));
        return picker;
    }

    protected Calendar getPersistedTime() {
        final Calendar c = Calendar.getInstance();
        c.setTimeInMillis(getPersistedLong(DEFAULT_VALUE));

        return c;
    }

    @Override
    protected void onBindDialogView(final View v) {
        super.onBindDialogView(v);
        final Calendar c = getPersistedTime();

        picker.setCurrentHour(c.get(Calendar.HOUR_OF_DAY));
        picker.setCurrentMinute(c.get(Calendar.MINUTE));
    }

    @Override
    protected void onDialogClosed(final boolean positiveResult) {
        super.onDialogClosed(positiveResult);

        if (positiveResult) {
            final Calendar c = Calendar.getInstance();
            c.set(Calendar.MINUTE, picker.getCurrentMinute());
            c.set(Calendar.HOUR_OF_DAY, picker.getCurrentHour());


            if (!callChangeListener(c.getTimeInMillis())) {
                return;
            }

            setTime(c.getTimeInMillis());
        }
    }

    @Override
    protected Object onGetDefaultValue(final TypedArray a, final int index) {
        return a.getInteger(index, 0);
    }

    @Override
    protected void onSetInitialValue(final boolean restorePersistedValue, final Object defaultValue) {
        long time;
        if (defaultValue == null) {
            time = restorePersistedValue ? getPersistedLong(DEFAULT_VALUE) : DEFAULT_VALUE;
        } else if (defaultValue instanceof Long) {
            time = restorePersistedValue ? getPersistedLong((Long) defaultValue) : (Long) defaultValue;
        } else if (defaultValue instanceof Calendar) {
            time = restorePersistedValue ? getPersistedLong(((Calendar)defaultValue).getTimeInMillis()) : ((Calendar)defaultValue).getTimeInMillis();
        } else {
            time = restorePersistedValue ? getPersistedLong(DEFAULT_VALUE) : DEFAULT_VALUE;
        }

        setTime(time);
        updateSummary(time);
    }

    @Override
    public boolean onPreferenceChange(final Preference preference, final Object newValue) {
        ((TimePreference) preference).updateSummary((Long)newValue);
        return true;
    }
}
Sam Whited
  • 6,880
  • 2
  • 31
  • 37
0

If you dont feel confortable storing time in millis, you can do this:

public void storeDate(Date theDate){
   SimpleDateFormat df = new SimpleDateFormat();
   df.applyPattern("yyyy/MM/dd HH:mm"); //this is the SQLite timedate pattern

   SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(MyActivity.this);
   pm.getEditor().putString("date_key", df.format(theDate));
}

public Date retrieveDate() {
   SimpleDateFormat df = new SimpleDateFormat();
   df.applyPattern("yyyy/MM/dd HH:mm"); //this is the SQLite timedate pattern

   SharedPreferences pm = PreferenceManager.getDefaultSharedPreferences(MyActivity.this);
   return df.parse(pm.getString("date_key"));  //this may throw an exception you should handle

}
juanmeanwhile
  • 2,594
  • 2
  • 24
  • 26