简体   繁体   中英

How to add points in textview using saved preferences and transfer these points to another textview after 24 hours?

My question seems to be too broad but let me try to make it short. I have two textviews as follows:

TextView 1: to contain points gained today

<TextView
                        android:id="@+id/pointsToday"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Points: 00" />

TextView 2: To contain points gained yesterday

<TextView
                        android:id="@+id/pointsYesterday"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:text="Points: 00" />

These points gained when I click the button, and in the button click listener I have this code which adds points

pointsValue = todayPoints + 1;
saveCoinss.edit().putFloat("$", (float) todayPoints).apply();

And i save my points in Saved Preferences with this method

SharedPreferences saveCoinss = this.getSharedPreferences("mySaverCoins", Context.MODE_PRIVATE);
    saveCoinss.edit().putFloat("$", (float) todayPoints).apply();

When i click the button my points display in TextView with is: android:id="@+id/pointsToday"

So now the problem is, I want to transfer these points from displaying in android:id="@+id/pointsToday" after a day (24 hours) and transfer them to textView with id android:id="@+id/pointsYesterday" . Which means by the beginning of the day the id/pointsToday will be 00 and id/pointsYesterday will take points that were in id/pointsToday. So how can i do this.

It can be solved better if you are using database, you can use Room for example.

Point.java

import android.arch.persistence.room.ColumnInfo;
import android.arch.persistence.room.Entity;
import android.arch.persistence.room.PrimaryKey;
import org.threeten.bp.OffsetDateTime;

@Entity(tableName = "point")
public class Point {
    @PrimaryKey(autoGenerate = true)
    private long id;
    @ColumnInfo(name = "value")
    private int value;
    @ColumnInfo(name = "point_date")
    private OffsetDateTime pointDate;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public int getValue() {
        return value;
    }

    public void setValue(int value) {
        this.value = value;
    }

    public OffsetDateTime getPointDate() {
        return pointDate;
    }

    public void setPointDate(OffsetDateTime pointDate) {
        this.pointDate = pointDate;
    }
}

PointDao.java

import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Delete;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.Query;
import java.util.List;

@Dao
public interface PointDao {

    @Query("SELECT * FROM point")
    List<Point> getAll();

    @Query("SELECT * FROM point WHERE id IN (:pointIds)")
    List<Point> getAllByIds(int[] pointIds);

    @Query("SELECT * FROM point WHERE point_date=date(:dateForSearch) LIMIT 1")
    Point getByPointDate(String dateForSearch);

    @Query("SELECT * FROM point ORDER BY point_date DESC LIMIT 1")
    Point getLastInsertedPoint();

    @Query("SELECT SUM(value) AS total_points FROM point")
    int getPointsSum();

    @Insert
    void insert(Point point);

    @Insert
    void insertAll(Point... points);

    @Insert
    void insertAll(List<Point> points);

    @Delete
    void delete(Point point);

    @Query("DELETE FROM point")
    void deleteAll();
}

See how easy to sum all of the values, by the method getPointsSum in class PointDao

AppDatabase.java

import android.arch.persistence.room.Database;
import android.arch.persistence.room.Room;
import android.arch.persistence.room.RoomDatabase;
import android.arch.persistence.room.TypeConverters;
import android.content.Context;

@Database(entities = {Point.class}, version = 1)
@TypeConverters(OffsetDateTimeConverter.class)
public abstract class AppDatabase extends RoomDatabase {
    private static AppDatabase INSTANCE;

    public abstract PointDao pointDao();

    public static AppDatabase getAppDatabase(Context context) {
        if (INSTANCE == null) {
            INSTANCE = Room.databaseBuilder(
                    context.getApplicationContext(),
                    AppDatabase.class,
                    "point-database"
            )
                    // allow queries on the main thread.
                    // Don't do this on a real app! See PersistenceBasicSample for an example.
                    .allowMainThreadQueries()
                    .build();
        }
        return INSTANCE;
    }

    public static void destroyInstance() {
        INSTANCE = null;
    }
}

OffsetDateTimeConverter.java

import android.arch.persistence.room.TypeConverter;
import android.text.TextUtils;
import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.format.DateTimeFormatter;

public class OffsetDateTimeConverter {
    private static final DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME;

    @TypeConverter
    public static OffsetDateTime toOffsetDate(String value) {
        if (!TextUtils.isEmpty(value)) {
            return formatter.parse(value, OffsetDateTime::from);
        }
        return null;
    }

    @TypeConverter
    public static String fromOffsetDate(OffsetDateTime date) {
        if (date != null) {
            return date.format(formatter);
        }
        return null;
    }
}

OffsetDateTimeChecker.java

import org.threeten.bp.OffsetDateTime;
import org.threeten.bp.format.DateTimeFormatter;
import org.threeten.bp.temporal.ChronoUnit;

public class OffsetDateTimeChecker {

    public static OffsetDateTime getYesterday() {
        return OffsetDateTime.now().minus(1, ChronoUnit.DAYS);
    }

    public static boolean isYesterday(OffsetDateTime offsetDateTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_OFFSET_DATE;
        String offsetDateTimeText = offsetDateTime.format(formatter);
        String yesterdayText = getYesterday().format(formatter);
        return yesterdayText.equals(offsetDateTimeText);
    }

    public static boolean isToday(OffsetDateTime offsetDateTime) {
        DateTimeFormatter formatter = DateTimeFormatter.ISO_LOCAL_DATE;
        String offsetDateTimeText = offsetDateTime.format(formatter);
        String todayText = OffsetDateTime.now().format(formatter);
        return todayText.equals(offsetDateTimeText);
    }
}

Add below dependencies to build.gradle of your app

def room_version = "1.1.0"
implementation "android.arch.persistence.room:runtime:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version"
testImplementation "android.arch.persistence.room:testing:$room_version"
implementation 'com.github.ThreeTen:threetenbp:v1.3.6'

I am using https://github.com/ThreeTen/threetenbp for the easier and faster performance and can support jdk6 and jdk7, but if you target android SDK26 and use java8, you can use the default provided by java8. Just remember that everything that stored in local device either it is a database or shared preferences can be hacked by the device owner. So you must implement your security mechanism for your saved data. You will also need to handle the timezone difference or if user cheating by changing the device time to get the point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM