【问题标题】:DatabaseReference not being fetched from Firestore未从 Firestore 获取 DatabaseReference
【发布时间】:2021-08-06 00:21:50
【问题描述】:

我正在尝试从我的 FireStore 数据库中显示以下信息 对于给定用户(当前用户),我想显示他们的“匹配”(其他用户的 id 和信息) 我还尝试了不同的结构,方法是在每个用户内部都有一个匹配数组(用户 ID 字符串)。 这就是我正在尝试的:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_matches);
        currentUserID = FirebaseAuth.getInstance().getCurrentUser().getUid();
        System.out.println("current user is: "+currentUserID);
        mRecyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        mRecyclerView.setNestedScrollingEnabled(false);
//      mRecyclerView.setHasFixedSize(true);
        mMatchesLayoutManager = new LinearLayoutManager(MatchesActivity.this);
        mRecyclerView.setLayoutManager(mMatchesLayoutManager);
        mMatchesAdapter = new MatchesAdapter(getDataSetMatches(), MatchesActivity.this);
        mRecyclerView.setAdapter(mMatchesAdapter);
        getUserMatchId();

    }
private void getUserMatchId() {
    DatabaseReference matchDb = FirebaseDatabase.getInstance().getReference().child("users").child(currentUserID).child("connections").child("matches");
    matchDb.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                for(DataSnapshot match : dataSnapshot.getChildren()){
                    System.out.println(match.toString());
                    FetchMatchInformation(match.getKey());
                }
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
}
private void FetchMatchInformation(String key) {
    DatabaseReference userDb = FirebaseDatabase.getInstance().getReference().child("users").child(key);
    userDb.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                String userId = dataSnapshot.getKey();
                String name = "";
                String profileIMageUrl = "";
                if(dataSnapshot.child("name").getValue()!=null){
                    name = dataSnapshot.child("name").getValue().toString();
                }
                if(dataSnapshot.child("profileImageUrl").getValue()!=null){
                    profileIMageUrl = dataSnapshot.child("profileImageUrl").getValue().toString();
                }
                MatchesObject obj = new MatchesObject(userId, name, profileIMageUrl);
                resultsMatches.add(obj);
                mMatchesAdapter.notifyDataSetChanged();
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
}

private ArrayList<MatchesObject> resultsMatches = new ArrayList<>();

private List<MatchesObject> getDataSetMatches() {
    return resultsMatches;
}

我尝试调试一下代码,我意识到在将侦听器添加到 matchDB 后没有任何反应 如果您能告诉我为什么没有显示任何内容以及如何正确访问匹配项,那就太好了。

【问题讨论】:

    标签: java database firebase android-studio google-cloud-firestore


    【解决方案1】:

    问题是您使用Firestore(将数据存储在集合和文档中)但使用Firebase Realtime Database 的代码(以类似JSON 的大格式存储数据)进行查询。

    要使用 Firestore,请确保您具有以下依赖项:

    dependencies {
        // Import the BoM for the Firebase platform
        implementation platform('com.google.firebase:firebase-bom:28.0.1')
    
        // Declare the dependency for the Cloud Firestore library
        // When using the BoM, you don't specify versions in Firebase library dependencies
        implementation 'com.google.firebase:firebase-firestore'
    }
    

    然后您可以尝试运行此代码从 Firestore 查询:

    firestore.collection("users").document(currentUserID).collection("connections")
            .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());
                        }
                    } else {
                        Log.d(TAG, "Error getting documents: ", task.getException());
                    }
                }
            });
    

    它应该记录连接集合中存在的所有文档的 ID。如果您实际上为每个连接存储一个单独的文档,而不是将所有 ID 存储在一个名为 match 的文档中的数组中,那么上面的代码就可以工作。如果您使用单个文档来存储大量 ID,则可能会超出文档的 1 MB 限制。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-09-29
      • 2020-03-23
      • 1970-01-01
      • 1970-01-01
      • 2017-06-09
      • 2021-10-18
      • 1970-01-01
      • 2021-10-13
      相关资源
      最近更新 更多