如何更新Firebase JSON节点中的特定字段

时间:2018-02-11 15:18:30

标签: java android json firebase firebase-realtime-database

我正在开发使用Firebase进行后端和数据库的Geo location Android应用程序。

这是我数据库中数据的结构。enter image description here

这是mu User.java类。

not an OLE2 structured storage file

我想做什么。

  • 我希望我的应用程序更新我目前正在使用的用户的JSON节点。这些是经度和纬度图片上显示的两个字段。

我现在怎么做?

  • 我现在正在从User.java类创建用户,然后通过setLongitude和setLatidude我添加数据然后调用setValue方法。
  • 以下是为此狙击的代码。

    @IgnoreExtraProperties
    public class User {
    
        public String fullName;
        public String email;
        public String longitude;
        public String latitude;
    
        public String getLongitude() {
            return longitude;
        }
    
        public void setLongitude(String longitude) {
            this.longitude = longitude;
        }
    
        public String getLatitude() {
            return latitude;
        }
    
        public void setLatitude(String latitude) {
            this.latitude = latitude;
        }
    
    
        public User() {
    
        }
    
        public String getFullName() {
            return fullName;
        }
    
        public void setFullName(String fullName) {
            this.fullName = fullName;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    

有什么问题?

  • 此刻我没有更新我的数据库,而是我最终删除了字段,然后添加了经度和纬度字段。这也显示在上图中。

1 个答案:

答案 0 :(得分:1)

问题是您在设置纬度和经度时没有设置fullName和电子邮件,那么这些字段为空。 setValue()将删除旧对象,并添加字段为null的新对象。您应该使用updateChildren代替setValue

Map<String, Object> latLong = new HashMap<>();
latLong.put("latitude", "123");
latLong.put("longitude", "123");

dbRef.child("users").child(currentUserId).updateChildren(latLong).addOnCompleteListener(new OnCompleteListener<Void>() {
            @Override
            public void onComplete(@NonNull Task<Void> task) {
                if (task.isSuccessful()) {
            Log.i("Info", "updateUser:success");
        } else {
            Log.i("Info", "updateUser:failure");
        }
            }
        });

如果您将电子邮件和fullName与纬度和经度一起设置,则可以继续使用您的代码。