I have an app,I want to allow user that click on a button just once in day. If the user change the date of phone can click on button again. What should i do this with shared Preference?
Asked
Active
Viewed 73 times
-3
-
Check this link to know about shared preferences http://stackoverflow.com/a/24772552/3843374 – Paritosh Sep 03 '14 at 05:41
1 Answers
1
On first time Button click store todays date and make the boolean true
which will make it non clickable :
if (prefs.getBoolean("ButtonClicked", false) == false) {
Date todaysDate = new Date();
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String lastFetchedDate = df.format(todaysDate);
Editor editor = prefs.edit();
editor.putString("ButtonClickedCheckDate", lastFetchedDate);
editor.putBoolean("ButtonClicked", true);
editor.commit();
}
Now to make it Click on next Day and make the boolean false
again -
Date currentDate = new Date();
String lastFetchedDate = prefs.getString("ButtonClickedCheckDate", null);
SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
String currentDateString = df.format(currentDate);
Date lastFetchedDateObj = null;
Date cureentDateObj = null;
try {
lastFetchedDateObj = df.parse(lastFetchedDate);
cureentDateObj = df.parse(currentDateString);
} catch (ParseException e) {
e.printStackTrace();
}
if (lastFetchedDate != null && cureentDateObj.after(lastFetchedDateObj)) {
Editor editor = prefs.edit();
editor.putBoolean("ButtonClicked", false);
editor.commit();
}

SilentKiller
- 6,944
- 6
- 40
- 75

Amresh
- 2,098
- 16
- 20
-
-
Go through http://developer.android.com/reference/java/text/SimpleDateFormat.html – Amresh Sep 03 '14 at 06:24