Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Room database, SELECT * FROM table by a given day

I'm using Room Persistence Library in my Android project, and store date using date type converter:

object DateConverter {
    @TypeConverter
    @JvmStatic
    fun fromTimestamp(value: Long?): Date? = if (null == value) null else Date(value)

    @TypeConverter
    @JvmStatic
    fun dateToTimestamp(date: Date?): Long? = date?.time
}

How could I select from my table by a given day using using Room DAO?

like image 844
Jan Slominski Avatar asked Nov 09 '17 10:11

Jan Slominski


3 Answers

 @Query("SELECT * FROM table_name WHERE date BETWEEN :dayst AND :dayet")
 Object getFromTable(long dayst, long dayet);

date dayst will be the timestamp for 00:00, i.e., 09/11/2017 00:00:00

date dayet will be the timestamp for 23:59, i.e., 09/11/2017 23:59:59

The Object is what you are getting from the database.

like image 88
joao86 Avatar answered Sep 18 '22 11:09

joao86


make it more simple.

  @Query("SELECT * FROM table_name WHERE date BETWEEN :daystart AND :dayend")
List<Student> fetchAllData(long start,long end);
like image 20
Syed Danish Haider Avatar answered Sep 18 '22 11:09

Syed Danish Haider


I have taken value of day, month and year by spinner. You can use it(With string and DateTypeConvertor instead Long) like this

At Dao :

@Query("SELECT * FROM MILKMANTABLE WHERE strftime('%Y',date) IN(:year) AND strftime('%m',date) IN(:month) AND strftime('%d',date) IN(:day)")

List<MilkMan> getMonthDetails(String day, String month, String year);

You can use this converter class to convert and save Date type to string in room table

DateTypeConverter :

public class DateConverter {
    static DateFormat df = new SimpleDateFormat(Constants.DOB_FORMAT);

    @TypeConverter
    public static Date fromTimestamp(String value) {
        if (value != null) {
            try {
                return df.parse(value);
            } catch (ParseException e) {
                e.printStackTrace();
            }
            return null;
        } else {
            return null;
        }
    }

    @TypeConverter
    public static String dateToTimestamp(Date value) {

        return value == null ? null : df.format(value);
    }
}

At Constants.java:

public static String DOB_FORMAT = "YYYY-MM-dd";
like image 40
Nik277 Avatar answered Sep 21 '22 11:09

Nik277