目標
在此代碼實驗室中,您將在由Cloud Firestore支持的Android上構建餐廳推薦應用程序。你將學到如何:
- 從Android應用讀取數據並將數據寫入Firestore
- 實時收聽Firestore數據中的更改
- 使用Firebase身份驗證和安全規則來保護Firestore數據
- 編寫複雜的Firestore查詢
先決條件
在開始此代碼實驗室之前,請確保您具有:
- Android Studio 4.0或更高版本
- 一個Android模擬器
- Node.js版本10或更高版本
- Java版本8或更高版本
- 使用您的Google帳戶登錄Firebase控制台。
- 在Firebase控制台中,單擊“添加項目” 。
- 如下圖所示,為您的Firebase項目輸入一個名稱(例如,“ Friendly Eats”),然後單擊“繼續” 。
- 可能會要求您啟用Google Analytics(分析),就此代碼實驗室而言,您的選擇無關緊要。
- 大約一分鐘後,您的Firebase項目將準備就緒。點擊繼續。
下載代碼
運行以下命令以克隆此代碼實驗室的示例代碼。這將在您的計算機上創建一個名為friendlyeats-android
的文件夾:
$ git clone https://github.com/firebase/friendlyeats-android
如果您的機器上沒有git,也可以直接從GitHub下載代碼。
將項目導入到Android的工作室。您可能會看到一些編譯錯誤,或者關於丟失的google-services.json
文件的警告。我們將在下一部分中對此進行更正。
添加Firebase配置
- 在Firebase控制台中,在左側導航欄中選擇“項目概述”。單擊Android按鈕以選擇平台。當提示輸入程序包名稱時,請使用
com.google.firebase.example.fireeats
- 點擊註冊應用,然後按照說明下載
google-services.json
文件,然後將其移至示例代碼的app/
文件夾中。然後單擊“下一步” 。
在此代碼實驗室中,您將使用Firebase Emulator Suite在本地模擬Cloud Firestore和其他Firebase服務。這提供了一個安全,快速,免費的本地開發環境來構建您的應用程序。
安裝Firebase CLI
首先,您需要安裝Firebase CLI 。最簡單的方法是使用npm
:
npm install -g firebase-tools
如果您沒有npm
或遇到錯誤,請閱讀安裝說明以獲取適用於您平台的獨立二進製文件。
安裝CLI後,運行firebase --version
應該報告9.0.0
或更高版本:
$ firebase --version 9.0.0
登錄
運行firebase login
以將CLI連接到您的Google帳戶。這將打開一個新的瀏覽器窗口,以完成登錄過程。確保選擇與先前創建Firebase項目時使用的帳戶相同的帳戶。
鏈接你的項目
在friendlyeats-android
文件夾中,運行firebase use --add
將本地項目連接到Firebase項目。按照提示選擇您之前創建的項目,如果要求選擇別名,請輸入default
。
現在是時候首次運行Firebase Emulator Suite和FriendlyEats Android應用程序了。
運行模擬器
在您的終端中,從friendlyeats-android
目錄中運行firebase emulators:start
以啟動Firebase Emulators。您應該看到這樣的日誌:
$ firebase emulators:start i emulators: Starting emulators: auth, firestore i firestore: Firestore Emulator logging to firestore-debug.log i ui: Emulator UI logging to ui-debug.log ┌─────────────────────────────────────────────────────────────┐ │ ✔ All emulators ready! It is now safe to connect your app. │ │ i View Emulator UI at http://localhost:4000 │ └─────────────────────────────────────────────────────────────┘ ┌────────────────┬────────────────┬─────────────────────────────────┐ │ Emulator │ Host:Port │ View in Emulator UI │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Authentication │ localhost:9099 │ http://localhost:4000/auth │ ├────────────────┼────────────────┼─────────────────────────────────┤ │ Firestore │ localhost:8080 │ http://localhost:4000/firestore │ └────────────────┴────────────────┴─────────────────────────────────┘ Emulator Hub running at localhost:4400 Other reserved ports: 4500 Issues? Report them at https://github.com/firebase/firebase-tools/issues and attach the *-debug.log files.
您現在已經在計算機上運行了完整的本地開發環境!確保在其餘的代碼實驗室中保持該命令的運行狀態,您的Android應用將需要連接至仿真器。
將應用程序連接到仿真器
在Android Studio中打開文件FirebaseUtil.java
。該文件包含將Firebase SDK連接到計算機上運行的本地仿真器的邏輯。
在文件頂部,檢查以下行:
/** Use emulators only in debug builds **/
private static final boolean sUseEmulators = BuildConfig.DEBUG;
我們使用BuildConfig
來確保僅在應用程序以debug
模式運行時才連接到仿真器。當我們在release
模式下編譯應用程序時,此條件將為false。
現在看一下getFirestore()
方法:
public static FirebaseFirestore getFirestore() {
if (FIRESTORE == null) {
FIRESTORE = FirebaseFirestore.getInstance();
// Connect to the Cloud Firestore emulator when appropriate. The host '10.0.2.2' is a
// special IP address to let the Android emulator connect to 'localhost'.
if (sUseEmulators) {
FIRESTORE.useEmulator("10.0.2.2", 8080);
}
}
return FIRESTORE;
}
我們可以看到它正在使用useEmulator(host, port)
方法將Firebase SDK連接到本地Firestore模擬器。在整個應用程序中,我們將使用FirebaseUtil.getFirestore()
訪問FirebaseFirestore
此實例,因此我們確保在debug
模式下運行時始終連接到Firestore模擬器。
運行應用
如果您已正確添加google-services.json
文件,則該項目現在應該可以編譯。在Android Studio中,單擊構建>重建項目,並確保沒有剩餘的錯誤。
在Android Studio中在Android模擬器上運行該應用程序。首先,您將看到一個“登錄”屏幕。您可以使用任何電子郵件和密碼登錄該應用程序。此登錄過程正在連接到Firebase身份驗證仿真器,因此不會傳輸任何真實憑證。
現在,通過在Web瀏覽器中導航到http:// localhost:4000 ,打開Emulators UI。然後單擊“身份驗證”選項卡,您應該看到剛創建的帳戶:
完成登錄過程後,您應該會看到應用程序主屏幕:
不久,我們將添加一些數據以填充主屏幕。
在本部分中,我們將一些數據寫入Firestore,以便我們可以填充當前為空的主屏幕。
我們應用程序中的主要模型對像是餐廳(請參閱model/Restaurant.java
)。 Firestore數據分為文檔,集合和子集合。我們將每個餐廳作為文檔存儲在稱為"restaurants"
的頂級集合中。要了解更多關於公司的FireStore數據模型,閱讀有關文件和收藏的文件。
出於演示目的,當我們單擊溢出菜單中的“添加隨機項目”按鈕時,我們將在應用程序中添加功能以創建十個隨機餐廳。打開文件MainActivity.java
並填寫onAddItemsClicked()
方法:
private void onAddItemsClicked() {
// Get a reference to the restaurants collection
CollectionReference restaurants = mFirestore.collection("restaurants");
for (int i = 0; i < 10; i++) {
// Get a random Restaurant POJO
Restaurant restaurant = RestaurantUtil.getRandom(this);
// Add a new document to the restaurants collection
restaurants.add(restaurant);
}
}
關於上面的代碼,需要注意一些重要的事情:
- 我們首先參考了
"restaurants"
系列。添加文檔時隱式創建集合,因此無需在寫入數據之前創建集合。 - 可以使用POJO創建文檔,我們使用POJO來創建每個餐廳文檔。
-
add()
方法將文檔添加到具有自動生成的ID的集合中,因此我們無需為每個Restaurant指定唯一的ID。
現在再次運行該應用程序,然後單擊溢出菜單中的“添加隨機項目”按鈕以調用您剛才編寫的代碼:
現在,通過在Web瀏覽器中導航到http:// localhost:4000 ,打開Emulators UI。然後單擊“ Firestore”選項卡,您應該看到剛剛添加的數據:
此數據是計算機本地100%的數據。實際上,您的真實項目甚至還不包含Firestore數據庫!這意味著可以安全地嘗試修改和刪除此數據而不會產生任何後果。
恭喜,您剛剛將數據寫入了Firestore!在下一步中,我們將學習如何在應用程序中顯示此數據。
在這一步中,我們將學習如何從Firestore檢索數據並將其顯示在我們的應用程序中。從Firestore讀取數據的第一步是創建Query
。修改onCreate()
方法:
mFirestore = FirebaseUtil.getFirestore();
// Get the 50 highest rated restaurants
mQuery = mFirestore.collection("restaurants")
.orderBy("avgRating", Query.Direction.DESCENDING)
.limit(LIMIT);
現在,我們想听查詢,以便獲取所有匹配的文檔,並實時收到將來更新的通知。因為我們最終的目標是將這些數據綁定到RecyclerView
,所以我們需要創建一個RecyclerView.Adapter
類來偵聽數據。
打開FirestoreAdapter
類,該類已經部分實現。首先,讓我們使適配器實現EventListener
並定義onEvent
函數,以便它可以接收對Firestore查詢的更新:
public abstract class FirestoreAdapter<VH extends RecyclerView.ViewHolder>
extends RecyclerView.Adapter<VH>
implements EventListener<QuerySnapshot> { // Add this "implements"
// ...
// Add this method
@Override
public void onEvent(QuerySnapshot documentSnapshots,
FirebaseFirestoreException e) {
// Handle errors
if (e != null) {
Log.w(TAG, "onEvent:error", e);
return;
}
// Dispatch the event
for (DocumentChange change : documentSnapshots.getDocumentChanges()) {
// Snapshot of the changed document
DocumentSnapshot snapshot = change.getDocument();
switch (change.getType()) {
case ADDED:
// TODO: handle document added
break;
case MODIFIED:
// TODO: handle document modified
break;
case REMOVED:
// TODO: handle document removed
break;
}
}
onDataChanged();
}
// ...
}
初始加載時,偵聽器將為每個新文檔接收一個ADDED
事件。隨著查詢結果集的變化,偵聽器將收到更多包含更改的事件。現在,讓我們完成實現偵聽器。首先添加三個新方法: onDocumentAdded
, onDocumentModified
和onDocumentRemoved
:
protected void onDocumentAdded(DocumentChange change) {
mSnapshots.add(change.getNewIndex(), change.getDocument());
notifyItemInserted(change.getNewIndex());
}
protected void onDocumentModified(DocumentChange change) {
if (change.getOldIndex() == change.getNewIndex()) {
// Item changed but remained in same position
mSnapshots.set(change.getOldIndex(), change.getDocument());
notifyItemChanged(change.getOldIndex());
} else {
// Item changed and changed position
mSnapshots.remove(change.getOldIndex());
mSnapshots.add(change.getNewIndex(), change.getDocument());
notifyItemMoved(change.getOldIndex(), change.getNewIndex());
}
}
protected void onDocumentRemoved(DocumentChange change) {
mSnapshots.remove(change.getOldIndex());
notifyItemRemoved(change.getOldIndex());
}
然後從onEvent
調用這些新方法:
@Override
public void onEvent(QuerySnapshot documentSnapshots,
FirebaseFirestoreException e) {
// ...
// Dispatch the event
for (DocumentChange change : documentSnapshots.getDocumentChanges()) {
// Snapshot of the changed document
DocumentSnapshot snapshot = change.getDocument();
switch (change.getType()) {
case ADDED:
onDocumentAdded(change); // Add this line
break;
case MODIFIED:
onDocumentModified(change); // Add this line
break;
case REMOVED:
onDocumentRemoved(change); // Add this line
break;
}
}
onDataChanged();
}
最後實現startListening()
方法來附加偵聽器:
public void startListening() {
if (mQuery != null && mRegistration == null) {
mRegistration = mQuery.addSnapshotListener(this);
}
}
現在,該應用已完全配置為從Firestore讀取數據。再次運行該應用程序,您應該會看到在上一步中添加的餐廳:
現在,返回瀏覽器中的Emulator UI並編輯餐廳名稱之一。您應該幾乎立即在應用程序中看到它的變化!
該應用程序當前顯示整個集合中評分最高的餐廳,但是在真實的餐廳應用程序中,用戶可能希望對數據進行排序和過濾。例如,該應用程序應該能夠顯示“費城頂級海鮮餐廳”或“最便宜的比薩”。
單擊應用程序頂部的白條,將顯示一個過濾器對話框。在本部分中,我們將使用Firestore查詢來使該對話框起作用:
讓我們編輯MainActivity.java
的onFilter()
方法。此方法接受一個Filters
對象,該對像是我們創建的用於捕獲過濾器對話框輸出的幫助對象。我們將更改此方法以從過濾器構造查詢:
@Override
public void onFilter(Filters filters) {
// Construct query basic query
Query query = mFirestore.collection("restaurants");
// Category (equality filter)
if (filters.hasCategory()) {
query = query.whereEqualTo("category", filters.getCategory());
}
// City (equality filter)
if (filters.hasCity()) {
query = query.whereEqualTo("city", filters.getCity());
}
// Price (equality filter)
if (filters.hasPrice()) {
query = query.whereEqualTo("price", filters.getPrice());
}
// Sort by (orderBy with direction)
if (filters.hasSortBy()) {
query = query.orderBy(filters.getSortBy(), filters.getSortDirection());
}
// Limit items
query = query.limit(LIMIT);
// Update the query
mQuery = query;
mAdapter.setQuery(query);
// Set header
mCurrentSearchView.setText(Html.fromHtml(filters.getSearchDescription(this)));
mCurrentSortByView.setText(filters.getOrderDescription(this));
// Save filters
mViewModel.setFilters(filters);
}
在上面的代碼段中,我們通過附加where
和orderBy
子句來匹配給定的過濾器來構建Query
對象。
再次運行該應用程序,然後選擇以下過濾器以顯示最受歡迎的低價餐廳:
現在,您應該會看到僅包含低價選擇的餐館的過濾列表:
如果到目前為止,您已經在Firestore上構建了功能齊全的餐廳推薦查看應用程序!您現在可以實時對餐廳進行分類和過濾。在接下來的幾節中,我們將評論和安全性發佈到應用程序中。
在本部分中,我們將為應用添加評分,以便用戶可以查看他們最喜歡(或最不喜歡)的餐館。
集合和子集合
到目前為止,我們已經將所有餐廳數據存儲在稱為“餐廳”的頂級集合中。當用戶對餐廳進行Rating
我們要向餐廳添加新的“ Rating
對象。對於此任務,我們將使用子集合。您可以將子集合視為附加到文檔的集合。因此,每個餐廳文檔都將具有一個完整的評分文件的評分子集合。子集合可幫助組織數據,而不會膨脹我們的文檔或要求復雜的查詢。
要訪問子集合,請在父文檔上調用.collection()
:
CollectionReference subRef = mFirestore.collection("restaurants")
.document("abc123")
.collection("ratings");
您可以像訪問頂級集合一樣訪問和查詢子集合,沒有大小限製或性能變化。您可以在此處閱讀有關Firestore數據模型的更多信息。
在事務中寫入數據
將Rating
添加到適當的子集合僅需要調用.add()
,但是我們還需要更新Restaurant
對象的平均評分和評分數量以反映新數據。如果我們使用單獨的操作來進行這兩個更改,則存在許多競爭條件,這些競爭條件可能會導致過時或錯誤的數據。
為了確保正確添加評級,我們將使用交易為餐館添加評級。該事務將執行一些操作:
- 閱讀餐廳的當前評分併計算新的評分
- 將評級添加到子集合
- 更新餐廳的平均評分和評分數
打開RestaurantDetailActivity.java
並實現addRating
函數:
private Task<Void> addRating(final DocumentReference restaurantRef,
final Rating rating) {
// Create reference for new rating, for use inside the transaction
final DocumentReference ratingRef = restaurantRef.collection("ratings")
.document();
// In a transaction, add the new rating and update the aggregate totals
return mFirestore.runTransaction(new Transaction.Function<Void>() {
@Override
public Void apply(Transaction transaction)
throws FirebaseFirestoreException {
Restaurant restaurant = transaction.get(restaurantRef)
.toObject(Restaurant.class);
// Compute new number of ratings
int newNumRatings = restaurant.getNumRatings() + 1;
// Compute new average rating
double oldRatingTotal = restaurant.getAvgRating() *
restaurant.getNumRatings();
double newAvgRating = (oldRatingTotal + rating.getRating()) /
newNumRatings;
// Set new restaurant info
restaurant.setNumRatings(newNumRatings);
restaurant.setAvgRating(newAvgRating);
// Commit to Firestore
transaction.set(restaurantRef, restaurant);
transaction.set(ratingRef, rating);
return null;
}
});
}
addRating()
函數返回代表整個事務的Task
。在onRating()
函數中,將偵聽器添加到任務中,以響應事務處理的結果。
現在,再次運行該應用程序,然後單擊其中一家餐廳,這將調出餐廳詳細信息屏幕。點擊+按鈕開始添加評論。通過選擇一些星星並輸入一些文字來添加評論。
點擊提交將啟動交易。交易完成後,您會在下面看到您的評論,並更新了該餐廳的評論數量:
恭喜!您現在有了一個在Cloud Firestore上構建的社交,本地,移動餐廳評論應用程序。我聽說這些天很受歡迎。
到目前為止,我們尚未考慮此應用程序的安全性。我們如何知道用戶只能讀寫正確的自己的數據? Firestore基準數據庫由名為“安全規則”的配置文件保護。
打開firestore.rules
文件,您應該看到以下內容:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
match /{document=**} {
//
// WARNING: These rules are insecure! We will replace them with
// more secure rules later in the codelab
//
allow read, write: if request.auth != null;
}
}
}
讓我們更改這些規則以防止不必要的數據訪問或更改,打開firestore.rules
文件,並將內容替換為以下內容:
rules_version = '2';
service cloud.firestore {
match /databases/{database}/documents {
// Determine if the value of the field "key" is the same
// before and after the request.
function isUnchanged(key) {
return (key in resource.data)
&& (key in request.resource.data)
&& (resource.data[key] == request.resource.data[key]);
}
// Restaurants
match /restaurants/{restaurantId} {
// Any signed-in user can read
allow read: if request.auth != null;
// Any signed-in user can create
// WARNING: this rule is for demo purposes only!
allow create: if request.auth != null;
// Updates are allowed if no fields are added and name is unchanged
allow update: if request.auth != null
&& (request.resource.data.keys() == resource.data.keys())
&& isUnchanged("name");
// Deletes are not allowed.
// Note: this is the default, there is no need to explicitly state this.
allow delete: if false;
// Ratings
match /ratings/{ratingId} {
// Any signed-in user can read
allow read: if request.auth != null;
// Any signed-in user can create if their uid matches the document
allow create: if request.auth != null
&& request.resource.data.userId == request.auth.uid;
// Deletes and updates are not allowed (default)
allow update, delete: if false;
}
}
}
}
這些規則限制了訪問權限,以確保客戶端僅進行安全更改。例如,更新餐廳文檔只能更改等級,不能更改名稱或任何其他不可變數據。僅當用戶ID與已登錄用戶匹配時才可以創建評級,這可以防止欺騙。
要了解有關安全規則的更多信息,請訪問文檔。
現在,您已經在Firestore上創建了功能齊全的應用程序。您了解了Firestore最重要的功能,包括:
- 文件和收藏
- 讀寫數據
- 查詢排序和過濾
- 子集合
- 交易次數
了解更多
為了繼續了解Firestore,這裡有一些入門的好地方:
此代碼實驗室中的restaurant應用程序基於“ Friendly Eats”示例應用程序。您可以在此處瀏覽該應用程序的源代碼。
可選:部署到生產
到目前為止,該應用程序僅使用了Firebase Emulator Suite。如果您想了解如何將此應用程序部署到真實的Firebase項目中,請繼續執行下一步。
到目前為止,該應用程序完全是本地的,所有數據都包含在Firebase Emulator Suite中。在本部分中,您將學習如何配置Firebase項目,以便該應用程序可以在生產環境中使用。
Firebase身份驗證
在Firebase控制台中,轉到“身份驗證”部分,然後導航至“登錄提供程序”選項卡。
啟用電子郵件登錄方法:
消防處
建立資料庫
導航到控制台的“ Firestore”部分,然後單擊“創建數據庫” :
- 當系統提示您選擇“以鎖定模式啟動安全規則”時,我們將盡快更新這些規則。
- 選擇您要用於應用程序的數據庫位置。請注意,選擇數據庫位置是一個永久性決定,要更改它,您將必須創建一個新項目。有關選擇項目位置的更多信息,請參見文檔。
部署規則
要部署您先前編寫的安全規則,請在codelab目錄中運行以下命令:
$ firebase deploy --only firestore:rules
這會將firestore.rules
的內容部署到您的項目中,您可以通過導航到控制台中的“規則”選項卡進行確認。
部署索引
FriendlyEats應用程序具有復雜的排序和過濾功能,這需要大量自定義復合索引。可以在Firebase控制台中手動創建這些文件,但是將它們的定義寫入firestore.indexes.json
文件並使用Firebase CLI進行部署更為簡單。
如果打開firestore.indexes.json
文件,您將看到已經提供了所需的索引:
{
"indexes": [
{
"collectionId": "restaurants",
"queryScope": "COLLECTION",
"fields": [
{ "fieldPath": "city", "mode": "ASCENDING" },
{ "fieldPath": "avgRating", "mode": "DESCENDING" }
]
},
{
"collectionId": "restaurants",
"queryScope": "COLLECTION",
"fields": [
{ "fieldPath": "category", "mode": "ASCENDING" },
{ "fieldPath": "avgRating", "mode": "DESCENDING" }
]
},
{
"collectionId": "restaurants",
"queryScope": "COLLECTION",
"fields": [
{ "fieldPath": "price", "mode": "ASCENDING" },
{ "fieldPath": "avgRating", "mode": "DESCENDING" }
]
},
{
"collectionId": "restaurants",
"queryScope": "COLLECTION",
"fields": [
{ "fieldPath": "city", "mode": "ASCENDING" },
{ "fieldPath": "numRatings", "mode": "DESCENDING" }
]
},
{
"collectionId": "restaurants",
"queryScope": "COLLECTION",
"fields": [
{ "fieldPath": "category", "mode": "ASCENDING" },
{ "fieldPath": "numRatings", "mode": "DESCENDING" }
]
},
{
"collectionId": "restaurants",
"queryScope": "COLLECTION",
"fields": [
{ "fieldPath": "price", "mode": "ASCENDING" },
{ "fieldPath": "numRatings", "mode": "DESCENDING" }
]
},
{
"collectionId": "restaurants",
"queryScope": "COLLECTION",
"fields": [
{ "fieldPath": "city", "mode": "ASCENDING" },
{ "fieldPath": "price", "mode": "ASCENDING" }
]
},
{
"collectionId": "restaurants",
"fields": [
{ "fieldPath": "category", "mode": "ASCENDING" },
{ "fieldPath": "price", "mode": "ASCENDING" }
]
}
],
"fieldOverrides": []
}
要部署這些索引,請運行以下命令:
$ firebase deploy --only firestore:indexes
請注意,索引創建不是即時的,您可以在Firebase控制台中監視進度。
配置應用
在FirebaseUtil
類中,我們將Firebase SDK配置為在調試模式下連接到仿真器:
public class FirebaseUtil {
/** Use emulators only in debug builds **/
private static final boolean sUseEmulators = BuildConfig.DEBUG;
// ...
}
如果您想用真實的Firebase項目測試您的應用程序,則可以:
- 在發布模式下構建應用程序,然後在設備上運行它。
- 暫時將
sUseEmulators
更改為false
並再次運行該應用程序。
請注意,您可能需要先退出應用程序,然後再次登錄才能正確連接到生產環境。