简体   繁体   中英

fetching data from firebase without using primary key of the table

I want to retrieve posts posted by currently loggedin user. But with current code all the posts are getting retrieved. How to retrieve expected data by using the uid from customer table?

post_id is primary key of Customer table not customerid(uid) .

Get a reference of the current user and use it to query post posted by the user like this:

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) {
                    }
                  });

    }

Try like this ,

Step 1. Get the right child node , and query on it by getting the current logded user 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) {

        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM