Search code examples
androidfirebasekotlinfirebase-realtime-databaseserialization

@PropertyName saves data but won't retrieve it with Firebase Realtime Database


import com.google.firebase.database.PropertyName

data class MyClass(
  @PropertyName(value = "n") 
  val name: String = "",
)

It works when you save data. On my database, the name was saved with the key "n", but when trying to get it, it's not read and I get an empty string because of the default constructor unless I change the actual name of the field to "n" which works in that case.

I'm using the Realtime Database.


Solution

  • If you want to set the name property as n, and you also want to read it as an n, then you have to explicitly add the annotation for both set and get in front of the property. So in your case, that would be:

    data class MyClass(
        @get:PropertyName("n")
        @set:PropertyName("n")
        var name: String = ""
    )