How to get MIN(date). using DAO query?

Viewed 233

I am new to Android Room Database. I saw there have similar questions on that topic, but i really didn't understand what actually worked for this topic. So, here I am trying to get the first date from the table, but while I query with that

@Query("select min(date) from user_items where userId = :userId ")
long getFirstDate(long userId);

I got the result as a minimum date is 01/01/1970 But i want the first date from the table to show the user.

My entity class User.java:

@Entity(tableName = "users")
public class User {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private String name;
    private String email;
    private String password;
    private String securityAnswer;

// other staff here
}

My another entity has a relation with User table.

UserItem.java:

@Entity(tableName = "user_items", indices = {@Index("userId")}, foreignKeys = @ForeignKey(entity = User.class,
        parentColumns = "id",
        childColumns = "userId",
        onDelete = CASCADE))
public class UserItems {
    @PrimaryKey(autoGenerate = true)
    private int id;
    private String category;
    private String amount;
    private String date;

    @ColumnInfo(name = "userId")
    private int userId;


// setter and getter
}

My other all query worked fine except min(date) function.

This is my entity, i want the first date as i marked, to show the user

2 Answers

Finally I got the solution: Here I change my query
Instead of this:

@Query("select min(date) from user_items where userId = :userId ")
long getFirstDate(long userId);

Use this:

@Query("select min(date) from user_items where userId = :userId ")
String getFirstDate(long userId);

Because if you look my UserItem.java class , here i am storing data as String so, if i want to store String to the long type, it's not allowed.

Hope it will help you.

The query is returning the start of the UNIX epoch (01/01/1970) which indicates that you might have persisted (or attempted to persist) an invalid value in the date column for one of your rows. You might want to check for any suspicious values in the date column.

Related