从Firebase获取数据而无需使用表的主键

时间:2018-09-03 13:08:44

标签: java android firebase firebase-realtime-database

我想检索当前登录用户发布的帖子。但是使用当前代码,所有帖子都将被检索。如何通过使用客户表中的uid检索期望的数据?

post_id是客户表的主键,而不是customerid(uid)

enter image description here

2 个答案:

答案 0 :(得分:0)

获取当前用户的引用,并使用它来查询用户发布的帖子,如下所示:

FirebaseUser user =FirebaseAuth.getInstance().getCurrentUser(); 
Query reference;

                       reference = FirebaseDatabase.getInstance().
                       getReference("customers").orderByChild("customerId").equalTo(user.getUid());


                       reference.addListenerForSingleValueEvent(new 
                       ValueEventListener() {
                       @Override
                       public void onDataChange(DataSnapshot dataSnapshot) {
                       for(DataSnapshot datas: dataSnapshot.getChildren()){
                       String 
                         customerId =datas.child("customerId").getValue().toString();

                       String 
                         customerName =datas.child("customerName").getValue().toString();

                       String 
                         phone =datas.child("phone").getValue().toString();


                      }
                    }

                    @Override
                    public void onCancelled(DatabaseError databaseError) {
                    }
                  });

    }

答案 1 :(得分:0)

尝试这样

步骤1.获取正确的子节点,并通过获取当前登录的用户uid对其进行查询:-

  String currentUser = FirebaseAuth.getInstance().getCurrentUser().getUid();

  DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("customers").orderByChild("customerId").equalTo(currentLoginId).addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Iterator<DataSnapshot> dataSnapshots = dataSnapshot.getChildren().iterator();
            List<Customers> customers = new ArrayList<>();
            while (dataSnapshots.hasNext()) {
                DataSnapshot dataSnapshotChild = dataSnapshots.next();
                Customers user = dataSnapshotChild.getValue(Customer.class);
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });