how to save datepicker to sharedpreferences

我们两清 提交于 2019-12-12 01:39:18

问题


Is there a way to save a datepicker data to sharedpreferences? If so, can you give me some codes on how to do it? I'm going to use datepicker to save user's date of birth. Any help would be appreciated.


回答1:


You can, in a roundabout way. From the year/month/day values of the DatePicker, construct a java.util.Date object. Then call getTime() on that object - it would return the date as a very long number (# of milliseconds since year 1970) as datatype long. Then you can store that in SharedPreferences using putLong() and retrieve it using getLong().

To place the date back into the picker, construct a Date object using the long value, then retrieve year/month/day from it.

Alternatively, you can save year/month/day as three separate preference items.

EDIT: here's a sample. The DatePicker object comes from somewhere in your app - I wouldn't know.

DatePicker dp; //Where does this come from? You tell me.
Date d = new Date(dp.getYear(), dp.getMonth(), dp.getDay());
SharedPreferences Prefs = PreferenceManager.getDefaultSharedPreferences(Ctxt);
Prefs.edit().putLong("Birthday", d.getTime()).commit();


来源:https://stackoverflow.com/questions/12162865/how-to-save-datepicker-to-sharedpreferences

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!