-3

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?

programmer
  • 13
  • 6

1 Answers1

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