【问题标题】:Save date to Shared Preferences将日期保存到共享首选项
【发布时间】:2014-01-11 22:55:47
【问题描述】:

我想将当前日期保存到我的列表视图中的文本视图中,我已经设置了所有其他内容,因此无需帮助,只需将日期保存到文本视图我的代码如下,有人可以告诉我有什么问题吗?

SharedPreferences settings =  PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
                SharedPreferences.Editor editor = settings.edit();
                editor.putLong("time", date.getTime());
                editor.commit();
                Date date2 = new Date(settings.getLong("time", 0));

【问题讨论】:

  • 你遇到了什么错误
  • @tyczj none 它只是不保存日期,而是明天它将我的列表视图中的所有日期设置为明天的日期听起来像我知道的 getView 和 .setText
  • 您的代码在我看来没问题。您是否调试过您发布的那部分。我很确定它工作正常。也许问题(ListView 中的日期?)出在其他地方?

标签: android android-listview android-fragments sharedpreferences


【解决方案1】:

我想说忘记日期和日历 - 只使用:

SharedPreferences settings =
    PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
settings.edit().putLong("time", System.currentTimeMillis()).commit();
// get the time and make a date out of it
Date date2 = new Date(settings.getLong("time", 0));

即在您的应用程序内部使用 currentTimeMillis(),如果您想向用户显示某些内容,只需使用 Date

永远不要在本地使用Calendar.getInstance() - 它很贵

如果您一直使用日期,请考虑 JodaTime

【讨论】:

  • 我是否放置日期 date2 = new Date(settings.getLong("time", 0));在活动的 onCreate 中??
  • @LimpLimp:你把它放在你需要的地方——那是为了得到从SP那里得到时间并从中确定日期——编辑帖子
【解决方案2】:

大多数 Date 类的方法已被弃用。您应该使用 Calendar 类。 Calendar c = Calendar.getInstance();

要存储在您的 SharedPreferences 中,我建议您存储一个很长的值,即由 c.getTimeInMillis(); 返回

要获取此日期并存储在日历对象中,您应该输入c.setTimeInMillis(myTimeStoredInSharedPreferences)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2022-01-15
    • 1970-01-01
    相关资源
    最近更新 更多