我已经通过Firestore的文档:https://firebase.google.com/docs/firestore/query-data/listen?authuser=0
但是在使用相同的代码时,我无法解析DocumentChange,EventListener等符号。 同样,我无法解析getDocumentChanges,getDocument,addSnapshotListener等方法。
我已经导入了com.google.firebase:firebase-admin:5.8.0'。
build.gradle文件
group 'firestore'
version '1.0-SNAPSHOT'
apply plugin: 'java'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
}
dependencies {
compile 'com.google.firebase:firebase-admin:5.8.0'
}
这是代码,我正在尝试:
package firestore;
import com.google.api.core.SettableApiFuture;
import com.google.firestore.v1beta1.DocumentChange;
import com.google.cloud.firestore.DocumentChange;
import com.google.cloud.firestore.DocumentChange.Type;
import com.google.cloud.firestore.EventListener;
import com.google.cloud.firestore.ListenerRegistration;
import com.google.cloud.firestore.Firestore;
import com.google.cloud.firestore.FirestoreException;
import com.google.cloud.firestore.Query;
import com.google.cloud.firestore.QuerySnapshot;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import javax.annotation.Nullable;
import static com.google.api.ChangeType.ADDED;
import static com.google.api.ChangeType.MODIFIED;
import static com.google.api.ChangeType.REMOVED;
/**
* Snippets to demonstrate Firestore 'listen' operations.
*/
@SuppressWarnings("Convert2Lambda")
public class FirestoreChange {
private static final long TIMEOUT_SECONDS = 5;
private final Firestore db;
FirestoreChange(Firestore db) {
this.db = db;
}
/**
* Listen to a query, returning the list of DocumentChange events in the first snapshot.
*/
List<DocumentChange> listenForChanges() throws Exception {
SettableApiFuture<List<DocumentChange>> future = SettableApiFuture.create();
// [START listen_for_changes]
db.collection("cities")
.whereEqualTo("state", "CA")
.addSnapshotListener(new EventListener<QuerySnapshot>() {
@Override
public void onEvent(@Nullable QuerySnapshot snapshots,
@Nullable FirestoreException e) {
if (e != null) {
System.err.println("Listen failed: " + e);
return;
}
for (DocumentChange dc : snapshots.getDocumentChanges()) {
switch (dc.getType()) {
case ADDED:
System.out.println("New city: " + dc.getDocument().getData());
break;
case MODIFIED:
System.out.println("Modified city: " + dc.getDocument().getData());
break;
case REMOVED:
System.out.println("Removed city: " + dc.getDocument().getData());
break;
default:
break;
}
}
// [START_EXCLUDE silent]
if (!future.isDone()) {
future.set(snapshots.getDocumentChanges());
}
// [END_EXCLUDE]
}
});
// [END listen_for_changes]
return future.get(TIMEOUT_SECONDS, TimeUnit.SECONDS);
}
}
答案 0 :(得分:1)
这种情况正在发生,因为您根本没有在build.gradle文件中添加Cloud Firestore依赖项。添加firebase-admin
不是为了让Firestore正常工作。所以要解决这个问题,只需添加以下代码:
compile 'com.google.firebase:firebase-firestore:11.8.0'
在firebase-admin
依赖项之后。同步您的项目,然后重试。