Reputation: 79735
I'm writing a small android app that lets the user pick a date and it shows him how many days are left to this date. Now I would like to store that date so that next time the app starts, it will keep the information. I was thinking it's probably best to save the date in a file, and my question is - how is it best to do this so it'll be easy to parse that date afterwards?
Upvotes: 2
Views: 145
Reputation: 33565
I speak from experience, The Best way to store a Date
is to store it's UNIX Epoch time,
SharedPreferences settings = getSharedPreferences("my_prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("date", myDate.getTime() ); //getTime is a long (So store it as a string/long, doesn't really matter)
editor.commit();
It'll save you the time/code from parsing it.
When retrieving the Date, just use the new Date(long date)
Constructor or the Calendar
class also has setTimeinMillis
.
Good Luck.
Upvotes: 2
Reputation: 48272
Save it to application preferences. In your Activity you might have somethign like:
PreferenceManager.getDefaultSharedPreferences(getApplicationContext()) .edit().putString("date", myDate.toString()).commit();
Then you restore your date from that saved string.
Upvotes: 0
Reputation: 521
Easiest way is probably to use the SharedPreferences:
Save in prefs:
SharedPreferences settings = getSharedPreferences("my_prefs", 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("date", myDate);
editor.commit();
Restore:
SharedPreferences settings = getSharedPreferences("my_prefs", 0);
String date = settings.getString("date", null);
Upvotes: 3