将数据写入Firebase,Android

时间:2018-02-16 09:36:44

标签: java android firebase firebase-realtime-database

我有一个使用Firebase的应用程序,它使用' push'写一条记录。我的问题是更新该记录的内容。任何帮助都非常欢迎。我使用Firebase Authentication电子邮件/密码,工作正常。我也有一个Java类的数据库也可以正常工作。在onCreate方法中,我引用了数据:

 databasePropertyData FirebaseDatabase.getInstance().getReference("users");

使用按钮我可以使用它的唯一标识符创建一条新记录,这就是我想要的:

    String ownerId = databasePropertyData.push().getKey();
    PropertyData propertyData = new PropertyData(ownerId, ownerName, name);
    databasePropertyData.child(ownerId).setValue(propertyData);

此代码工作正常,并根据需要使用用户ID创建记录。

但是,我现在想要更新该特定记录,这就是问题所在。我使用的代码(以及无数的变体)设置了一条新记录而不是更新现有数据。这是我失败的实验的一个例子:

   String ownerId = databasePropertyData.getKey();
   databasePropertyData.child(ownerId).setValue(name,ownerName);

非常感谢任何帮助。

4 个答案:

答案 0 :(得分:2)

这种情况正在发生,因为您使用的是 func numberOfLinesInLabel(yourString: String, labelWidth: CGFloat, labelHeight: CGFloat, font: UIFont) -> Int { let paragraphStyle = NSMutableParagraphStyle() paragraphStyle.minimumLineHeight = labelHeight paragraphStyle.maximumLineHeight = labelHeight paragraphStyle.lineBreakMode = .ByWordWrapping let attributes: [String: AnyObject] = [NSFontAttributeName: font, NSParagraphStyleAttributeName: paragraphStyle] let constrain = CGSizeMake(labelWidth, CGFloat(Float.infinity)) let size = yourString.sizeWithAttributes(attributes) let stringWidth = size.width let numberOfLines = ceil(Double(stringWidth/constrain.width)) return Int(numberOfLines) } 方法。每次登录时都会生成一个新的随机密钥。要解决此问题,请使用push()而不是按下的密钥。

uid

使用PropertyData propertyData = new PropertyData(ownerId, ownerName, name); String uid = FirebaseAuth.getInstance().getCurrentUser().getUid(); databasePropertyData.child(uid).setValue(propertyData); 的好处是您可以非常轻松地更新记录。

uid

答案 1 :(得分:0)

您可以使用updateChild更新指定的字段,这里是ref: https://firebase.google.com/docs/database/web/read-and-write#update_specific_fields

答案 2 :(得分:0)

String ownerId = databasePropertyData.getKey();

此处不应创建新的ownerId,而应使用要更新的propertyData的相同ID。然后使用updateChildrensetValue方法,您可以更新该值。 然后这将工作正常:

databasePropertyData = FirebaseDatabase.getInstance().getReference("users");
PropertyData propertyData = new PropertyData(ownerId, ownerName, name);
databasePropertyData.child(ownerId).setValue(propertyData);

答案 3 :(得分:0)

你的数据库中有这个:

 users
   randomid
       ownerId: 12345
       ownerName: userx
       name: anothername

要进行更新,您可以执行此操作,因为您使用的是push(),然后使用包含密钥的变量并执行此操作:

String ownerId = databasePropertyData.push().getKey(); //the variable that has the key, not a new variable
PropertyData propertyData = new PropertyData(ownerId, ownerName, name);
databasePropertyData.child(ownerId).setValue(propertyData);

或者代替此,您可以更改数据库结构并使用用户ID:

     FirebaseUser user=FirebaseAuth.getInstance().getCurrentUser();
     PropertyData propertyData = new PropertyData(ownerId, ownerName, name);
    databasePropertyData.child(ownerId).setValue(propertyData);

或者您可以进行查询并从数据库中检索push()密钥并更新查询中的值。

但你必须更新所有3个字段。