Reputation: 3919
I'm using Cloud Firestore with Android Studio. I've noticed that it seems to save every field in a class to the database, not just to ones that have setters/getters. How do I stop this from happening?
For example, let's say I have a class called Box
, defined like this:
private class Box {
private int id;
private String name, label;
public Box(){}
public void setId(int thisId) {id = thisId;}
public void setName(String thisName) { name = thisName;}
public int getId() { return id;}
public String getName { return name;}
public setup label () { ... }
}
I only have setters and getters for id and name, because they're the ones I want to save to the database. I don't want to save label, because it changes each time. However, it's saving it anyway, with a value of null.
What am I doing wrong? How do I stop it from saving a value for label?
Upvotes: 0
Views: 1290
Reputation: 41
Didn't work for me. So, I put @Exclude annotation before the getter method of the field I want to exclude from writing to Firestore db, and it worked:
@Exclude
public String getId() {
return id;
}
And remove @Exclude from the variable declaration, if it is an private modifier
Upvotes: 2
Reputation: 138969
There is no way to use default object serialization and also selectively remove properties that don't meet your criteria. Object serialization uses all available object properties all the time, regardless of their values. Unlike in Firebase Realtime database, where non-existing values are not displayed at all, in Cloud Firestore, if you create an object without setting its value, Firestore will assign the value of null
.
If you don't want a value to be present in your database at all, you can use @Grimthorr's answer as @tyczj suggested in his comment.
To avoid having null
properties in your database, as also @Raj suggested, you should use a Map
containing only the properties of the document that you want to store. More important, you should also check each value for null
, if you don't want to store null
for a field. It is the only in which you can achieve this.
From the official documentation, this is how it should look like in code:
Map<String, Object> city = new HashMap<>();
city.put("name", "Los Angeles");
city.put("state", "CA");
city.put("country", "USA");
db.collection("cities").document("LA").set(city);
If your app is already launched and you have null
values in your database, you can create a map and use FieldValue.delete()
like this:
Map<String, Object> map = new HashMap<>();
map.put("yourField", FieldValue.delete());
yourRef.update(map);
The fields with null
values won't be displayed anymore.
Upvotes: 1
Reputation: 3001
You can use map to set the variables you want. Then send that map to firestore.
Map<String, Object> map = new HashMap<String, Object>();
map.put("id", "value");
map.put("name", "value");
firestore.collection("Your_collection_name).document(uid).add(map)...`
then you can add success listener or complete listener.
Upvotes: 1