1

我想將當前日期保存到我的列表視圖中的一個textview我有一切設置,所以沒有必要幫助那裏只需將日期保存到textview我的代碼如下有人可以告訴我什麼錯?將日期保存到共享首選項

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)); 
+1

錯誤,你得到什麼 – tyczj

+0

@tyczj沒有它只是不節能的日期,而不是明天它會將我的列表視圖中的所有日期設置爲明天的日期聽起來像我知道的getView和.setText – LimpLimp

+0

您的代碼對我來說看起來沒問題。你有沒有調試過你發佈的那部分。我很確定它工作正常。也許這個問題(在ListView中的日期?)在其他地方? – Ridcully

回答

4

Date類的大多數方法已被棄用。你應該使用Calendar類。

要保存在你的SharedPreferences,我建議你保存很長,至極再來通過c.getTimeInMillis();

獲取此日期和存儲在日曆對象中,你應該把c.setTimeInMillis(myTimeStoredInSharedPreferences)

1

我d說忘記了關於日期和日曆 - 只使用:

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()內部,如果喲只是使用日期ü要顯示的東西給用戶

切勿使用Calendar.getInstance()地方 - 如果使用日期所有的時間考慮JodaTime它是昂貴的

+0

我把日期date2 =新日期(settings.getLong(「時間」,0));在活動的onCreate? – LimpLimp

+0

@LimpLimp:你把它放在你需要它的地方 - 這是爲了_getting_從SP的時間,並從它做出一個日期 - 編輯帖子 –