0

I am trying to select data from my database and I want to check if a specific child node has a one or a zero as it's value. If it has a 1 then I don't want to show info from that specific user. If it has a zero then I want to show info from that specific user.

I did it in a method above the one I'm working on(I followed this answer How to get child of child value from firebase in android?) and I got it working no problem. But I can't do the same for my other method and I have been trying all day now.

As of right now, the only result I am getting is the list not showing up at all. Can someone please help me ?

Method that works:

private void getPosts() {

    followingList = new ArrayList<>();

    DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Video_Posts");
    FirebaseUser firebaseUser = FirebaseAuth.getInstance().getCurrentUser();

    reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            myPosts.clear();
            //followingList.clear();
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

                Post post = snapshot.getValue(Post.class);
                if (followingList.isEmpty()) {

                    if (!post.getPublisher().equals(firebaseUser.getUid())) {

                        DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("Users");
                        DatabaseReference zone1Ref = zonesRef.child(post.getPublisher());
                        DatabaseReference zone1NameRef = zone1Ref.child("acc_closed");

                        zone1NameRef.addValueEventListener(new ValueEventListener() {
                            @Override
                            public void onDataChange(DataSnapshot dataSnapshot) {
                                //Log.i(TAG, dataSnapshot.getValue(String.class));

                                if (dataSnapshot.getValue(String.class).equals("1")) {

                                    //Toast.makeText(getContext(), "Account closed", Toast.LENGTH_SHORT).show();
                                } else if (dataSnapshot.getValue(String.class).equals("0")) {

                                    //Toast.makeText(getContext(), "Not closed.", Toast.LENGTH_SHORT).show();

                                    DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();

                                    Query query = rootRef
                                            .child("Follow")
                                            .child(firebaseUser.getUid())
                                            .child("following")
                                            .child(post.getPublisher());

                                    ValueEventListener valueEventListener = new ValueEventListener() {
                                        @Override
                                        public void onDataChange(DataSnapshot dataSnapshot) {
                                            if (dataSnapshot.exists()) {
                                                //Do something
                                                Toast.makeText(getContext(), "Following.", Toast.LENGTH_SHORT).show();

                                            } else {
                                                //Do something else
                                                myPosts.add(post);
                                                Collections.shuffle(myPosts);
                                                //Toast.makeText(getContext(), "Something.", Toast.LENGTH_SHORT).show();
                                            }
                                        }

                                        @Override
                                        public void onCancelled(DatabaseError databaseError) {
                                        }
                                    };
                                    query.addListenerForSingleValueEvent(valueEventListener);
                                }
                            }

                            @Override
                            public void onCancelled(DatabaseError databaseError) {
                                //Log.w(TAG, "onCancelled", databaseError.toException());
                            }
                        });

                    } else if (myPosts == null) {
                        Toast.makeText(getContext(), "Nothing.", Toast.LENGTH_SHORT).show();
                    }

                } else {
                    Toast.makeText(getContext(), "List is not empty.", Toast.LENGTH_SHORT).show();

                    for (String id : followingList) {

                        assert post != null;
                        if (!post.getPublisher().equals(id)) {
                            myPosts.add(post);
                            Toast.makeText(getContext(), "Something.", Toast.LENGTH_SHORT).show();

                        } else if (myPosts == null) {
                            Toast.makeText(getContext(), "Nothing.", Toast.LENGTH_SHORT).show();
                        }
                    }
                }
            }

            adapterExplorer.notifyDataSetChanged();
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onCancelled(@NonNull DatabaseError error) {
        }
    });
}

Method that doesn't work:

private void searchUsers(String s) {

    Query query = FirebaseDatabase.getInstance().getReference("Users");

    query.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

            if (search_bar.getText().toString().equals("")) {
                recyclerView.setVisibility(View.INVISIBLE);
            }

            mUsers.clear();
            for (DataSnapshot snapshot : dataSnapshot.getChildren()) {

                User user = snapshot.getValue(User.class);

                DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("Users");
                DatabaseReference zone1Ref = zonesRef.child(user.getId());
                DatabaseReference zone1NameRef = zone1Ref.child(user.getAcc_closed());

                //mUsers.add(user);
                zone1NameRef.addValueEventListener(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot snapS) {

                        if (snapS.getKey().equals("1")) {

                        } else if (snapS.getKey().equals("0")){

                            //if (!snapS.exists()) {
                                Log.d("TAG", snapS.toString());
                                mUsers.add(user);
                            //}
                        }
                        //}
                    }

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

                        Log.d("Error name", error.getMessage());
                    }
                });
            }

            userAdapter.notifyDataSetChanged();
        }

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

            Log.d("Error name", error.getMessage());
        }
    });
}

Database:

"Users": {
"4mFQt8Lf3CTNrQF74sy8wwyFoLh1": {
  "acc_closed": "0",
  "bio": "",
  "dateAdded": "19-06-2022 17:28:56",
  "date_time": 1655674136805,
  "device_token": "feGjHNzaR7S8yaV2HKg0rt:APA91bEXAiYwT52niHVxR2ENrcaKXSNs11Z5ss-g2gsDwTs4wbjqjcrN4ZUmemqiMzp6SZM6UXD5TFrc1JND_DoEgd-Ni9wMeCa73EzvKBAaj5aXJf1GjgjSsTVwBg1A6VvhvVwF1VSX",
  "fullname": "Brandon",
  "id": "4mFQt8Lf3CTNrQF74sy8wwyFoLh1",
  "imageurl": "https://firebasestorage.googleapis.com/v0/b/gone-b14f5.appspot.com/o/default.jpg?alt=media&token=befece91-9248-45ee-ab6f-b1b3d217c6b4",
  "username": "bran1",
  "verified": "false"
},

EDIT:

The code above (searchUsers) kind of works. When I put text into the search bar nothing shows up. But when I hit the back button and remove the keyboard the data shows up. It's like I'm actually waiting for data to change.

sergpetrov
  • 1,506
  • 1
  • 11
  • 20
His R.H
  • 19
  • 1
  • 5
  • 1
    What exactly in this code doesn't work the way you expect? Tell us what is wrong with shared code. Do you have any errors? – Alex Mamo Jul 18 '22 at 06:56
  • @AlexMamo I don't know I don't get any errors or anything but the second method doesn't work. I'm expecting it to me a list of users who didn't delete their account `acc_closed == "1"` but it's not showing me any of the users – His R.H Jul 18 '22 at 07:04
  • How do you know that you're getting no error? So first of all, stop ignoring them. At a minimum, please add `Log.d(TAG, error.getMessage());`. Do you get something printed out in the logcat? – Alex Mamo Jul 18 '22 at 07:14
  • @AlexMamo No still nothing. – His R.H Jul 18 '22 at 07:22
  • Hey @HisR.H Stack Overflow is a notoriously inefficient interactive debugger, so it's most likely we can help if you do the debugging on your own and then edit the question (there's a link right under it) to show what results you got. So: show the updated `onCancelled` so we can see you now handle errors (as Alex suggested), and add some more `Log` calls to the other code to see what executes and what doesn't, and what values all (important) parameters have. With those, it'll be much more likely one of us can help. – Frank van Puffelen Jul 18 '22 at 13:53
  • One of the things missing here is what the data at path `Users` in your database looks like. In addition to what I asked above, make sure to also add this data (as text, no screenshots please). You can get this by clicking the "Export JSON" link in the overflow menu (⠇) on your [Firebase Database console](https://console.firebase.google.com/project/_/database/data). – Frank van Puffelen Jul 18 '22 at 13:57
  • @FrankvanPuffelen hello I updated the question. I checked my logcat but still no errors. – His R.H Jul 18 '22 at 19:00
  • I added this `Log.d(TAG, String.valueOf(user.getId()));` to the `zone1NameRef.addValueEventListener` and I'm getting the output but I don't know why it's not showing up – His R.H Jul 18 '22 at 19:08

1 Answers1

0

The simple fix is that you should call notifyDataSetChanged after you modified the data that the adapter shows, where right now you're calling it before that.

So move the call to userAdapter.notifyDataSetChanged() to right after mUsers.add(user):

Query query = FirebaseDatabase.getInstance().getReference("Users");

query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (search_bar.getText().toString().equals("")) {
            recyclerView.setVisibility(View.INVISIBLE);
        }

        mUsers.clear();
        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
            User user = snapshot.getValue(User.class);

            DatabaseReference zonesRef = FirebaseDatabase.getInstance().getReference("Users");
            DatabaseReference zone1Ref = zonesRef.child(user.getId());
            DatabaseReference zone1NameRef = zone1Ref.child(user.getAcc_closed());

            zone1NameRef.addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(@NonNull DataSnapshot snapS) {

                    if (snapS.getKey().equals("1")) {

                    } else if (snapS.getKey().equals("0")){
                        Log.d("TAG", snapS.toString());
                        mUsers.add(user);
                        userAdapter.notifyDataSetChanged(); // 
                    }
                }

                @Override
                public void onCancelled(@NonNull DatabaseError error) {
                    Log.d("Error name", error.getMessage());
                }
            });
        }
    }

There is some more (but not related to the problem) room for optimization here, as the dataSnapshot you get in the outermost listener already contains the data for *alldata under/Users`.

So there's no need to add an other listener to get the acc_closed value for each user. Instead you can just navigate the initial snapshot like this:

Query query = FirebaseDatabase.getInstance().getReference("Users");

query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (search_bar.getText().toString().equals("")) {
            recyclerView.setVisibility(View.INVISIBLE);
        }

        mUsers.clear();
        for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
            DataSnapshot snapS = userSnapshot.child("acc_closed");
            String accClose = snapS.getValue(String.class)
            if (accClose.equals("0")){
                Log.d("TAG", accClose);
                mUsers.add(userSnapshot.getValue(User.class));
                userAdapter.notifyDataSetChanged();
            }
        }
    }

Finally: your code retrieves all /Users to then only use the users who have acc_close being equal to "0". This wastes (your and your user's) bandwidth, especially as you're adding more users. It's much better to use a query to retrieve only the necessary data from the server/database:

DatabaseReference usersRef = FirebaseDatabase.getInstance().getReference("Users");
Query query = usersRef.orderByChild("acc_closed").equalTo("0");

query.addValueEventListener(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        if (search_bar.getText().toString().equals("")) {
            recyclerView.setVisibility(View.INVISIBLE);
        }

        mUsers.clear();
        for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
            mUsers.add(userSnapshot.getValue(User.class));
        }
        userAdapter.notifyDataSetChanged();

    }
Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807