Darkstorm51
Darkstorm51

Reputation: 35

Android/Java Firebase adding unexpected value to key/reference

Let me start by saying that I am very new to using Firebase.

I am trying to push a custom object with a string called "mGameSessionID" to my Firebase Database using push():

DatabaseReference pushedPostRef = 
myRef.child(myRef.push().getKey());

String gameSessionID = pushedPostRef.getKey();

GameSession gameSession = new GameSession(gameSessionID);

pushedPostRef.setValue(gameSession);

However when setting the value using ".setValue(gameSession)" it adds an extra gameSessionID value to the database

Example picture of what the firebase looks like

Here is the GameSession class:

String mGameSessionID;

GameSession()
{

}

GameSession(String gameSessionID)
{
    mGameSessionID = gameSessionID;
}

public String getGameSessionID() 
{
    return mGameSessionID;
}

public void setGameSessionID(String gameSessionID) 
{
    mGameSessionID = gameSessionID;
}

Upvotes: 0

Views: 79

Answers (1)

Doug Stevenson
Doug Stevenson

Reputation: 317467

The Firebase Realtime Database SDK will serialize all visible fields and JavaBean-type getter methods on an instance of an object using reflection to discover them. So, if it sees a field "foo", it will serialize a property called "foo". If it sees a getter method called "getFoo", it will serialize a property also called "foo".

For JavaBean type objects like your GameSession, fields with accessors (getters and setters) should be private, with access only allowed through them:

private String mGameSessionID

This should prevent the SDK from seeing mGameSessionId, and instead only use the visible getter method for it.

Upvotes: 1

Related Questions