本文檔介紹了讀取和寫入Firebase數據的基礎知識。
Firebase數據將寫入FirebaseDatabase
引用,並通過將異步偵聽器附加到該引用進行檢索。數據的初始狀態會觸發一次偵聽器,並且在數據更改時會再次觸發。
獲取數據庫參考
要從數據庫讀取或寫入數據,您需要一個DatabaseReference
實例:
爪哇
private DatabaseReference mDatabase; // ... mDatabase = FirebaseDatabase.getInstance().getReference();
Kotlin + KTX
private lateinit var database: DatabaseReference // ... database = Firebase.database.reference
讀寫數據
基本寫操作
對於基本寫操作,可以使用setValue()
將數據保存到指定的引用,從而替換該路徑上的任何現有數據。您可以使用此方法執行以下操作:
- 與可用的JSON類型相對應的傳遞類型如下:
-
String
-
Long
-
Double
-
Boolean
-
Map<String, Object>
-
List<Object>
-
- 如果定義它的類具有不帶參數的默認構造函數,並且具有要分配的屬性的公共獲取器,則傳遞一個自定義Java對象。
如果使用Java對象,則對象的內容將以嵌套方式自動映射到子位置。使用Java對象通常還可以使您的代碼更具可讀性,並且更易於維護。例如,如果您的應用程序具有基本的用戶配置文件,則您的User
對象可能如下所示:
爪哇
@IgnoreExtraProperties public class User { public String username; public String email; public User() { // Default constructor required for calls to DataSnapshot.getValue(User.class) } public User(String username, String email) { this.username = username; this.email = email; } }
Kotlin + KTX
@IgnoreExtraProperties data class User( var username: String? = "", var email: String? = "" )
您可以使用setValue()
添加用戶,如下所示:
爪哇
private void writeNewUser(String userId, String name, String email) { User user = new User(name, email); mDatabase.child("users").child(userId).setValue(user); }
Kotlin + KTX
private fun writeNewUser(userId: String, name: String, email: String?) { val user = User(name, email) database.child("users").child(userId).setValue(user) }
以這種方式使用setValue()
覆蓋指定位置(包括所有子節點)上的數據。但是,您仍然可以更新子項而無需重寫整個對象。如果要允許用戶更新其個人資料,則可以如下更新用戶名:
爪哇
mDatabase.child("users").child(userId).child("username").setValue(name);
Kotlin + KTX
database.child("users").child(userId).child("username").setValue(name)
聆聽價值事件
要在路徑上讀取數據並偵聽更改,請使用addValueEventListener()
或addListenerForSingleValueEvent()
方法將ValueEventListener
添加到DatabaseReference
。
聽眾 | 事件回調 | 典型用法 |
---|---|---|
ValueEventListener | onDataChange() | 讀取和偵聽路徑全部內容的更改。 |
您可以使用onDataChange()
方法讀取給定路徑上內容的靜態快照,因為它們在事件發生時就已經存在。附加了偵聽器後,將觸發此方法,而每次更改數據(包括子級)時,都會觸發此方法。將向事件回調傳遞快照,該快照包含該位置的所有數據,包括子數據。如果沒有數據,快照將返回false
,當你調用exists()
和null
當你調用getValue()
就可以了。
以下示例演示了一個社交博客應用程序,該應用程序從數據庫中檢索帖子的詳細信息:
爪哇
ValueEventListener postListener = new ValueEventListener() { @Override public void onDataChange(DataSnapshot dataSnapshot) { // Get Post object and use the values to update the UI Post post = dataSnapshot.getValue(Post.class); // ... } @Override public void onCancelled(DatabaseError databaseError) { // Getting Post failed, log a message Log.w(TAG, "loadPost:onCancelled", databaseError.toException()); // ... } }; mPostReference.addValueEventListener(postListener);
Kotlin + KTX
val postListener = object : ValueEventListener { override fun onDataChange(dataSnapshot: DataSnapshot) { // Get Post object and use the values to update the UI val post = dataSnapshot.getValue<Post>() // ... } override fun onCancelled(databaseError: DatabaseError) { // Getting Post failed, log a message Log.w(TAG, "loadPost:onCancelled", databaseError.toException()) // ... } } postReference.addValueEventListener(postListener)
偵聽器會在事件發生時收到一個DataSnapshot
,其中包含數據庫中指定位置的數據。在快照上調用getValue()
將返回數據的Java對象表示形式。如果該位置不存在任何數據,則調用getValue()
返回null
。
在此示例中, ValueEventListener
還定義了ValueEventListener
onCancelled()
方法,如果取消讀取,則會調用該方法。例如,如果客戶端沒有從Firebase數據庫位置讀取的權限,則可以取消讀取。此方法傳遞了一個DatabaseError
對象,該對象指示發生故障的原因。
一次讀取數據
在某些情況下,您可能希望先調用一次回調,然後立即將其刪除,例如在初始化您不希望更改的UI元素時。您可以使用addListenerForSingleValueEvent()
方法簡化這種情況:它觸發一次,然後不再觸發。
這對於只需要加載一次且不會經常更改或需要主動監聽的數據很有用。例如,前面示例中的博客應用程序使用此方法在用戶開始撰寫新帖子時加載其個人資料:
更新或刪除數據
更新特定字段
要同時寫入節點的特定子節點而不覆蓋其他子節點,請使用updateChildren()
方法。
調用updateChildren()
,可以通過指定鍵的路徑來更新較低級別的子值。如果數據存儲在多個位置以更好地擴展,則可以使用數據扇出更新該數據的所有實例。例如,社交博客應用程序可能具有這樣的Post
類:
爪哇
@IgnoreExtraProperties public class Post { public String uid; public String author; public String title; public String body; public int starCount = 0; public Map<String, Boolean> stars = new HashMap<>(); public Post() { // Default constructor required for calls to DataSnapshot.getValue(Post.class) } public Post(String uid, String author, String title, String body) { this.uid = uid; this.author = author; this.title = title; this.body = body; } @Exclude public Map<String, Object> toMap() { HashMap<String, Object> result = new HashMap<>(); result.put("uid", uid); result.put("author", author); result.put("title", title); result.put("body", body); result.put("starCount", starCount); result.put("stars", stars); return result; } }
Kotlin + KTX
@IgnoreExtraProperties data class Post( var uid: String? = "", var author: String? = "", var title: String? = "", var body: String? = "", var starCount: Int = 0, var stars: MutableMap<String, Boolean> = HashMap() ) { @Exclude fun toMap(): Map<String, Any?> { return mapOf( "uid" to uid, "author" to author, "title" to title, "body" to body, "starCount" to starCount, "stars" to stars ) } }
為了創建帖子並同時將其更新為最近的活動提要和發布用戶的活動提要,博客應用程序使用如下代碼:
爪哇
private void writeNewPost(String userId, String username, String title, String body) { // Create new post at /user-posts/$userid/$postid and at // /posts/$postid simultaneously String key = mDatabase.child("posts").push().getKey(); Post post = new Post(userId, username, title, body); Map<String, Object> postValues = post.toMap(); Map<String, Object> childUpdates = new HashMap<>(); childUpdates.put("/posts/" + key, postValues); childUpdates.put("/user-posts/" + userId + "/" + key, postValues); mDatabase.updateChildren(childUpdates); }
Kotlin + KTX
private fun writeNewPost(userId: String, username: String, title: String, body: String) { // Create new post at /user-posts/$userid/$postid and at // /posts/$postid simultaneously val key = database.child("posts").push().key if (key == null) { Log.w(TAG, "Couldn't get push key for posts") return } val post = Post(userId, username, title, body) val postValues = post.toMap() val childUpdates = hashMapOf<String, Any>( "/posts/$key" to postValues, "/user-posts/$userId/$key" to postValues ) database.updateChildren(childUpdates) }
此示例使用push()
在節點中創建一個帖子,該帖子包含/posts/$postid
所有用戶的/posts/$postid
並同時使用getKey()
檢索密鑰。然後可以使用該密鑰在/user-posts/$userid/$postid
的用戶帖子中創建第二個條目。
使用這些路徑,您可以通過一次調用updateChildren()
來同時更新JSON樹中的多個位置,例如本示例在兩個位置中創建新帖子的方式。通過這種方式進行的同時更新是原子性的:要么所有更新成功,要么所有更新失敗。
添加完成回調
如果您想知道何時提交數據,則可以添加完成偵聽器。 setValue()
和updateChildren()
帶有一個可選的完成偵聽器,當寫入成功提交到數據庫後,將調用該偵聽器。如果調用失敗,則向偵聽器傳遞一個錯誤對象,指示發生失敗的原因。
爪哇
mDatabase.child("users").child(userId).setValue(user) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { // Write was successful! // ... } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { // Write failed // ... } });
Kotlin + KTX
database.child("users").child(userId).setValue(user) .addOnSuccessListener { // Write was successful! // ... } .addOnFailureListener { // Write failed // ... }
刪除資料
刪除數據的最簡單方法是在對數據位置的引用上調用removeValue()
。
您還可以通過將null
指定為另一個寫操作(例如setValue()
或updateChildren()
的值來刪除。您可以將此技術與updateChildren()
以在單個API調用中刪除多個子級。
分離聽眾
通過調用Firebase數據庫參考上的removeEventListener()
方法可以刪除回調。
如果已將偵聽器多次添加到數據位置,則每個事件將多次調用該偵聽器,並且必須將其分離相同的次數才能將其完全刪除。
在父偵聽removeEventListener()
上調用removeEventListener()
不會自動刪除在其子節點上註冊的偵聽器。還必須在任何子偵聽removeEventListener()
上調用removeEventListener()
才能刪除回調。
將數據另存為交易
當使用可能被並發修改破壞的數據(例如增量計數器)時,可以使用事務操作。您為該操作提供了兩個參數:更新函數和可選的完成回調。更新函數將數據的當前狀態作為參數,並返回您要寫入的新的所需狀態。如果另一個客戶端在成功寫入新值之前寫入該位置,則將使用新的當前值再次調用更新函數,然後重試寫入。
例如,在示例社交博客應用程序中,您可以允許用戶為帖子加註星標和取消注星,並跟踪帖子獲得了多少星標,如下所示:
爪哇
private void onStarClicked(DatabaseReference postRef) { postRef.runTransaction(new Transaction.Handler() { @Override public Transaction.Result doTransaction(MutableData mutableData) { Post p = mutableData.getValue(Post.class); if (p == null) { return Transaction.success(mutableData); } if (p.stars.containsKey(getUid())) { // Unstar the post and remove self from stars p.starCount = p.starCount - 1; p.stars.remove(getUid()); } else { // Star the post and add self to stars p.starCount = p.starCount + 1; p.stars.put(getUid(), true); } // Set value and report transaction success mutableData.setValue(p); return Transaction.success(mutableData); } @Override public void onComplete(DatabaseError databaseError, boolean committed, DataSnapshot currentData) { // Transaction completed Log.d(TAG, "postTransaction:onComplete:" + databaseError); } }); }
Kotlin + KTX
private fun onStarClicked(postRef: DatabaseReference) { postRef.runTransaction(object : Transaction.Handler { override fun doTransaction(mutableData: MutableData): Transaction.Result { val p = mutableData.getValue(Post::class.java) ?: return Transaction.success(mutableData) if (p.stars.containsKey(uid)) { // Unstar the post and remove self from stars p.starCount = p.starCount - 1 p.stars.remove(uid) } else { // Star the post and add self to stars p.starCount = p.starCount + 1 p.stars[uid] = true } // Set value and report transaction success mutableData.value = p return Transaction.success(mutableData) } override fun onComplete( databaseError: DatabaseError?, committed: Boolean, currentData: DataSnapshot? ) { // Transaction completed Log.d(TAG, "postTransaction:onComplete:" + databaseError!!) } }) }
如果多個用戶同時對同一個帖子加註星標或客戶端具有陳舊的數據,則使用事務可防止星級計數不正確。如果交易被拒絕,則服務器將當前值返回給客戶端,客戶端將使用更新後的值再次運行交易。重複此操作,直到接受交易或進行過多嘗試為止。
離線寫入數據
如果客戶端失去網絡連接,則您的應用將繼續正常運行。
連接到Firebase數據庫的每個客戶端都維護任何活動數據的內部版本。寫入數據後,首先將其寫入此本地版本。然後,Firebase客戶端將根據“最大努力”與遠程數據庫服務器和其他客戶端同步該數據。
結果,所有寫入數據庫的操作都會在任何數據寫入服務器之前立即觸發本地事件。這意味著您的應用程序始終保持響應狀態,無論網絡延遲或連接性如何。
重新建立連接後,您的應用將接收適當的事件集,以便客戶端與當前服務器狀態同步,而無需編寫任何自定義代碼。