Home » Android » android – How to compare Firebase datasnapshot value and show data in list-Exceptionshub

android – How to compare Firebase datasnapshot value and show data in list-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

Screenshot

Basically there is a string value currentuserid which contains the UNIQUE ID of user.

There are many child items in “notifications”

I only want to show data that is of currentuser only. Is it correct?

My code so far..

    DatabaseReference dbReff = database.getReference("notifications");
    dbReff.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            if (dataSnapshot.exists()){
                for (DataSnapshot npsnapshot : dataSnapshot.getChildren()){

                    if(currentUserId.equals(npsnapshot.child("id").getValue()))
                    {
                        ListData l = npsnapshot.getValue(ListData.class);
                        listData.add(l);
                    }

                    else
                    {
                        Toast.makeText(getApplicationContext(),"No notifications",Toast.LENGTH_LONG).show();
                    }
                }
                adapter=new MyAdapter(listData);
                rv.setAdapter(adapter);
                adapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {

        }
    });
How to&Answers:

You can compare the data based on your current user id in server side using orderByChild and equalTo method provided by firebase. Check below:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("notifications");
databaseReference.orderByChild("id").equalTo(currentUserId).addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

        for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {

            ListData l = childSnapshot.getValue(ListData.class);
            listData.add(l);
        }

        ....
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});