3

我需要将日期对象放在共享首选项编辑器中。

将其转换为什么数据类型以存储在共享首选项中?通常我们 prefEditor.putString("Idetails1", Idetails1);为字符串和元素编写。

我怎么做?我也可以将它用于日期对象吗?

private EditText pDisplayDate;
private ImageView pPickDate;
private int pYear;
private int pMonth;
private int pDay;
/** This integer will uniquely define the dialog to be used for displaying date picker.*/
static final int DATE_DIALOG_ID = 0;

Date date;

private DatePickerDialog.OnDateSetListener pDateSetListener =
new DatePickerDialog.OnDateSetListener() {
    public void onDateSet(DatePicker view, int year, 
    int monthOfYear, int dayOfMonth) {
       pYear = year;
       pMonth = monthOfYear;
       pDay = dayOfMonth;
       updateDisplay();
       displayToast();
    }
};

private void updateDisplay() {
    pDisplayDate.setText(
       new StringBuilder()
       // Month is 0 based so add 1
       .append(pMonth + 1).append("/")
       .append(pDay).append("/")
       .append(pYear).append(" ")
    );
}

private void displayToast() {
    Toast.makeText(this, 
        new StringBuilder()
        .append("Date choosen is ")
        .append(pDisplayDate.getText()),
        Toast.LENGTH_SHORT).show();
}
4

2 回答 2

6

can i use this for date object too??

The simpliest way i think you can use is convert Date to its String representation. Then you can simply convert it back to Date object using some date formatter.

String dateString = date.toString();
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(<context>);
p.edit().putString("date", dateString).commit();

Update:

Also how @MCeley pointed out, you can also convert Date to long and put its long value:

long dateTime = date.getTime();
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(<context>);
p.edit().putLong("date", dateTime).commit();
于 2013-04-01T12:21:34.517 回答
0

每当它更改或从 Preference 对象检索易于使用时,使用 Calendar 对象设置日期。

Calendar c = Calendar.getInstance(); // use system date on first time for initialization.

long millis= pref.getLong("date",c.getTimeInMillis()); // retrieve date from Preference object in long format

c.setTimeInMillis(millis); // now set in calendar and then use it

//on date change set the year, month and day into calendar to and then stored in preference

private DatePickerDialog.OnDateSetListener pDateSetListener =
        new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, 
                                  int monthOfYear, int dayOfMonth) {
                pYear = year;
                pMonth = monthOfYear;
                pDay = dayOfMonth;
                c.set(pYear , pMonth , pDay ); // set into the calendar and when need to save in preference do this
                Editor edit = pref.editor();
                edit.put("date",c.getTimeInMillis());
                edit.commit();
                updateDisplay();
                displayToast();
            }
        };
于 2013-04-01T12:26:01.393 回答