Android Cloud Firestore - Real-time database

Cloud Firestore是一個靈活,可擴展的數據庫,用於從FirebaseGoogle Cloud Platform進行移動,Web和服務器開發。與Firebase實時數據庫一樣,它可以通過實時監聽器使您的數據在客戶端應用程序之間保持同步,並為移動和Web提供離線支持,因此您可以構建響應式應用程序,無論網絡延遲或Internet連接如何,都能正常運行。Cloud Firestore還提供與其他FirebaseGoogle Cloud Platform產品的無縫集成,包括雲功能。


Cloud Firestore目前處於測試Beta階段。


創建Cloud Firestore項目

  1. 打開Firebase控制台並創建一個新項目。
  2. 在“ 數據庫”部分中,單擊“ Cloud Firestore” “入門”按鈕。
  3. 選擇Cloud Firestore安全規則的啟動模式:
    測試模式
    適合開始使用移動和Web客戶端庫,但允許任何人讀取和覆蓋您的數據。測試後,請務必查看“ 保護您的數據”部分。
    要開始使用Web,IOS或Android SDK,請選擇測試模式。
    鎖定模式
    拒絕來自移動和Web客戶端的所有讀取和寫入。經過身份驗證的應用程序服務器(C#,Go,Java,Node.js,PHP,Python或Ruby)仍可以訪問您的數據庫。
    要開始使用C#,Go,Java,Node.js,PHP,Python或Ruby服務器客戶端庫,請選擇鎖定模式。
  4. 單擊啟用
Cloud Firestore和App Engine: 您不能在同一項目中同時使用Cloud Firestore和Cloud Datastore,這可能會影響使用App Engine的應用程序。嘗試將Cloud Firestore與其他項目一起使用。

設置您的開發環境

  1. 按照說明 將Firebase添加到您的Android應用中
  2. 將Cloud Firestore Android庫添加到您的app/build.gradle文件中:
implementation 'com.google.firebase:firebase-firestore:17.1.5'

初始化Cloud Firestore

// Access a Cloud Firestore instance from your Activity
FirebaseFirestore db = FirebaseFirestore.getInstance();

添加數據 

有幾種方法可以將數據寫入Cloud Firestore:
  • Add將新文檔添加到集合中。 在這種情況下,Cloud Firestore會自動生成文檔標識符(document identifier)。
  • Set在集合中設置文檔的數據,當您使用set()創建一個文檔,必須指定文件創建一個ID。
  • Update在集合中更新文檔的數據,更新文檔的某些字段而不覆蓋整個文檔。

Add - 當你使用 set() 去創建一個文檔時,必須指定document id,但有時文檔沒有有意義的ID,讓Cloud Firestore自動為您生成ID更方便。你可以通過調用 add():

add的參數除了使用Map集合的方式,也可以直接丟入你的類別,例如 .add(new user("ada", "Lovelace", 1815))
// Create a new user with a first and last name
Map<string object=""> user = new HashMap<>();
user.put("first", "Ada");
user.put("last", "Lovelace");
user.put("born", 1815);

// Add a new document with a generated ID
db.collection("users")
        .add(user)
        .addOnSuccessListener(new OnSuccessListener<documentreference>() {
            @Override
            public void onSuccess(DocumentReference documentReference) {
                Log.d(TAG, "DocumentSnapshot added with ID: " + documentReference.getId());
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error adding document", e);
            }
        });

Set - 要創建或覆蓋單個文檔,請使用 set() 方法:

Map<string object=""> city = new HashMap<>();
city.put("name", "Los Angeles");
city.put("state", "CA");
city.put("country", "USA");

db.collection("cities").document("LA")
        .set(city)
        .addOnSuccessListener(new OnSuccessListener<void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "DocumentSnapshot successfully written!");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error writing document", e);
            }
        });
如果該文檔不存在,則將創建該文檔。 如果文檔確實存在,則其內容將被新提供的數據覆蓋,除非您指定數據應合併到現有文檔中,如下所示:
// Update one field, creating the document if it does not already exist.
Map<String, Object> data = new HashMap<>();
data.put("capital", true);

db.collection("cities").document("BJ")
        .set(data, SetOptions.merge());
如果您不確定文檔是否存在,請傳遞選項以將新數據與任何現有文檔合併,以避免覆蓋整個文檔。

Update - 要更新文檔的某些字段而不覆蓋整個文檔,請使用 update() 方法:

更新部分字段,如果文檔不存在,則會失敗
DocumentReference washingtonRef = db.collection("cities").document("DC");

// Set the "isCapital" field of the city 'DC'
washingtonRef
        .update("capital", true)
        .addOnSuccessListener(new OnSuccessListener<void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "DocumentSnapshot successfully updated!");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error updating document", e);
            }
        });

Update fields in nested objects - 更新較複雜的物件

如果文檔包含嵌套對象,則在調用update()時可以使用“點表示法”引用文檔中的嵌套字段:
// Assume the document contains:
// {
//   name: "Frank",
//   favorites: { food: "Pizza", color: "Blue", subject: "recess" }
//   age: 12
// }
//
// To update age and favorite color:
db.collection("users").document("frank")
        .update(
                "age", 13,
                "favorites.color", "Red"
        );
您還可以將服務器時間戳添加到文檔中的特定字段,以跟踪服務器何時收到更新:
// If you're using custom Java objects in Android, add an @ServerTimestamp
// annotation to a Date field for your custom object classes. This indicates
// that the Date field should be treated as a server timestamp by the object mapper.
DocumentReference docRef = db.collection("objects").document("some-id");

// Update the timestamp field with the value from the server
Map<String,Object> updates = new HashMap<>();
updates.put("timestamp", FieldValue.serverTimestamp());

docRef.update(updates).addOnCompleteListener(new OnCompleteListener<Void>() {
    // ...
    // ...

Update elements in an array - 更新資料陣列

如果您的文檔包含數組字段,則可以使用 arrayUnion() arrayRemove() 來添加和刪除元素。 arrayUnion() 將元素添加到數組中,但只添加元素。 arrayRemove() 刪除每個給定元素的所有實例。
DocumentReference washingtonRef = db.collection("cities").document("DC");

// Atomically add a new region to the "regions" array field.
washingtonRef.update("regions", FieldValue.arrayUnion("greater_virginia"));

// Atomically remove a region from the "regions" array field.
washingtonRef.update("regions", FieldValue.arrayRemove("east_coast"));

讀取數據

要快速驗證是否已將數據添加到Cloud Firestore,請使用Firebase控制台中的數據查看器 。
您還可以使用“get”方法來檢索整個集合。
db.collection("users")
        .get()
        .addOnCompleteListener(new OnCompleteListener<querysnapshot>() {
            @Override
            public void onComplete(@NonNull Task<querysnapshot> task) {
                if (task.isSuccessful()) {
                    for (QueryDocumentSnapshot document : task.getResult()) {
                        Log.d(TAG, document.getId() + " => " + document.getData());
                    }
                } else {
                    Log.w(TAG, "Error getting documents.", task.getException());
                }
            }
        });

刪除數據

要刪除文檔,請使用delete()方法:
db.collection("cities").document("DC")
        .delete()
        .addOnSuccessListener(new OnSuccessListener<void>() {
            @Override
            public void onSuccess(Void aVoid) {
                Log.d(TAG, "DocumentSnapshot successfully deleted!");
            }
        })
        .addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                Log.w(TAG, "Error deleting document", e);
            }
        });

Delete fields

To delete specific fields from a document, use the FieldValue.delete() method when you update a document:
DocumentReference docRef = db.collection("cities").document("BJ");

// Remove the 'capital' field from the document
Map<String,Object> updates = new HashMap<>();
updates.put("capital", FieldValue.delete());

docRef.update(updates).addOnCompleteListener(new OnCompleteListener<void>() {
    // ...
    // ...


這樣試玩用下來,感覺FireStore更完整,更好用了

留言

這個網誌中的熱門文章

Android - 使用 adb 安装apk

Android ContentProvider 實現多個應用程式共享資料

Android TextView autosizing 自動調整大小