簡體   English   中英

將數據寫入Firebase,Android

[英]Writing data to Firebase, Android

我有一個使用Firebase的應用程序,它使用“推”來編寫記錄。 我的問題是更新該記錄的內容。 任何幫助都非常歡迎。 我正在使用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);

任何幫助將非常感激。

發生這種情況是因為您使用的是push()方法。 每當您登錄時,它都會生成一個新的隨機密鑰。要解決此問題,請使用uid而不是按下的鍵。

PropertyData propertyData = new PropertyData(ownerId, ownerName, name);
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
databasePropertyData.child(uid).setValue(propertyData);

使用uid的好處是您可以非常輕松地更新記錄。

databasePropertyData.child(uid).updateChildren(propertyData);

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

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);

您的數據庫中有這個:

 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);

或代替此,您可以更改數據庫結構並使用用戶標識:

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

或者,您可以進行查詢並從數據庫中檢索push()鍵並更新查詢中的值。

但是您必須更新所有3個字段。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM