user3385947
user3385947

Reputation: 43

How to make a counter add only once a day (android)?

Hello I've made android application which lets the user upload a photo taken on the application to facebook or lets them save the photo to the phone but I wanted to add a "score".

So if someone uploaded or saved a photo they'd get a point but I want to limit the points gained to one point a day and I'm not sure how I'd go about doing this.

Upvotes: 4

Views: 559

Answers (1)

Tautvydas
Tautvydas

Reputation: 2067

You can have a SharedPreference value that holds last photo save timestamp in milliseconds. Then whenever a user saves a photo check the preference value, if it's today then do nothing and if its other day then add score to user and update preference value to the new timestamp.

Here is the code structure with the Joda DateTime.

public void onSavePhoto() {
    SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
    long lastSaveTime = settings.getLong("last_save", 0);
    int lastDay = new DateTime(lastSaveTime).getDayOfYear();
    int today = DateTime.now().getDayOfYear();

    if (lastDay < today) {
        //add score
        addScore();
        //update preference value
        SharedPreferences.Editor editor = settings.edit();
        editor.putLong("last_save", today);
    }
}

Upvotes: 5

Related Questions