How to use Joda DateTime date as id in Room, or how to get date in query?

泪湿孤枕 提交于 2019-12-13 03:14:41

问题


I need to write an app that uses date as id, and I must be able to update just by comparing date

@Entity
data class DailyCount(@PrimaryKey
                  var date:DateTime,
                  var summ: Double = 0.0)

And here is the DAO

@Query("update DailyCount set summ = :sum where date = :today")
fun updateCash(today: DateTime, sum: Double)

I want to make like this :

@Entity
data class DailyCount(@PrimaryKey
                  var date:Date,//JodaTime containing only date
                  var summ: Double = 0.0)

Or like this:

@Query("update DailyCount set summ = :sum where date.today = :dateArg.today")
fun updateCash(dateArg: DateTime, sum: Double)

回答1:


Room doesn't know how to save your primary field DateTime into database.

You need to write a TypeConverter.

public class TypeConverter {
    private static Gson gson = new Gson();

    @TypeConverter
    public static DateTime stringToDate(String data) {

        Type type = new TypeToken<DateTime>() {
        }.getType();

        return gson.fromJson(data, type);
    }

    @TypeConverter
    public static String dateToString(DateTime dateTime) {
        return gson.toJson(dateTime);
    }
}

Then annotate your primary key

@PrimaryKey
@TypeConverters(TypeConverter::class.java)
var date:DateTime



回答2:


I was needed to write this query :

@Query("update DailyCount set summ = :sum where date between  :startTimeOfDay and :endTimeOfDay")
fun updateCash(startTimeOfDay: DateTime, endTimeOfDay: DateTime, sum: Double)

I gave here a range with start and end time. This approach returns true when I want to set info in today's Id



来源:https://stackoverflow.com/questions/56051963/how-to-use-joda-datetime-date-as-id-in-room-or-how-to-get-date-in-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!