2

I've a simple data class of User

data class User(@PrimaryKey(autoGenerate = true) val id: Long, val _id: String, val name: String, val about: String,
                    val phoneNumber: String, val token: String,
                    val lastLogin: String, val avatarUrl: String, @Embedded val location: Location,
                    val emailId: String, val gender: Boolean, val timestamp: Long = System.currentTimeMillis())

As you can see the last parameter is val timestamp: Long = System.currentTimeMillis()

the response comes from network using retrofit and parsed using GSON

timestamp does not comes in a response json it's just extra field I need to do some logic. The problem is that value is always 0. It should be the current time stamp

Sunny
  • 14,522
  • 15
  • 84
  • 129
  • 3
    See here: https://stackoverflow.com/a/39963353/1103872 – Marko Topolnik Aug 17 '18 at 11:48
  • so I need to use another library just for a little change. gson is already being used all over the place in the app and using two different lib for same purpose does not make sense. – Sunny Aug 17 '18 at 12:24
  • Maybe it starts making sense once you realize that GSON calls `Unsafe.allocateObject()` to create your object without calling any initialization code mandated by the actual class. You hack, you lose. However, a way out for you could be to ensure that your class gets compiled with the default constructor. GSON will then call it instead of the dirty `Unsafe` hack. – Marko Topolnik Aug 17 '18 at 12:51

1 Answers1

2

This will do the trick,

data class User(@PrimaryKey(autoGenerate = true) val id: Long, val _id: String, val name: String, val about: String,
                val phoneNumber: String, val token: String,
                val lastLogin: String, val avatarUrl: String, @Embedded val location: Location,
                val emailId: String, val gender: Boolean) {
    var timestamp: Long = System.currentTimeMillis()
    get() = if(field > 0) field else {
        field = System.currentTimeMillis()
        field
    }
}
Randheer
  • 984
  • 6
  • 24
  • Hi sorry but it'll give me latest timestamp every time. The response is saved in db with timestamp and when getting user again from db the get method override and will give current time stamp. – Sunny Aug 17 '18 at 12:21
  • I can't say this is most efficient way, but I have updated my answer to handle your case. Do accept answer if it helps. Thanks. – Randheer Aug 17 '18 at 12:47
  • it shows https://imgur.com/a/u9WthHj –  Aug 17 '18 at 13:08
  • Just Change val to var, I have updated answer. This will make warning go away. I hope this way it worked. – Randheer Aug 17 '18 at 13:32