How to skip null/empty variables in the firestore collection?

*爱你&永不变心* 提交于 2020-05-14 19:57:31

问题


Like firebase real-time database, I don't want store null/empty value in firestore collection .so how i can skip or remove null fields from firestore collection

below function save data to firestore

private void saveTofireStore(String path, User userObject,Class<?> classType){

    FirebaseFirestore db = FirebaseFirestore.getInstance();
    documentReference = db.document(path);
    Log.d(TAG,""+documentReference.getPath());
   documentReference
            .set(userObject)
            .addOnCompleteListener(task -> {
                if (task.isSuccessful()){
                  appearanceMutableLiveData.setValue(task.getResult());
                }else {
                    appearanceMutableLiveData.setValue(null);
                }
            });

}

回答1:


I found an easy way using Gson to serialize object then convert into the map then you can save that object

private Map<String, Object> removeNullValues(User userObject) {
    Gson gson = new GsonBuilder().create();

    Map<String, Object> map = new Gson().fromJson(
            gson.toJson(userObject), new TypeToken<HashMap<String, Object>>() {
            }.getType()
    );

    return map;
}

and then

documentReference
.set( removeNullValues( userObject) )
.addOnSuccessListener {}


来源:https://stackoverflow.com/questions/51216441/how-to-skip-null-empty-variables-in-the-firestore-collection

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