简体   繁体   中英

Trying to retrieve data from firebase where the category is equal to the string

I am trying to retrieve data from the Firebase Realtime Database and I only want where the category is equal to a String. For example, if my string is football then I should get all the data that has the category football in it. I run my app with the code I am about to show you but I get nothing but a blank page. I don't know what I am doing wrong.

 databaseReference = FirebaseDatabase.getInstance().getReference();
    if (Categories.InternetConnection.checkConnection(Categories.this)) {

        databaseReference.child("Sports").orderByChild("category").equalTo("football")).addValueEventListener(new ValueEventListener() {


            @Override
            public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                    myUploads.clear();

                for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
                    for (DataSnapshot postsnapshot : userSnapshot.getChildren()) {
                        Model_Information upload = postsnapshot.getValue(Model_Information.class);
                     
                        Collections.shuffle(myUploads);
                      
                        myUploads.add(upload);
                        recyclerView.invalidate();
                    }
                }
                    linearLayoutWithoutItems.setVisibility(View.GONE);
                    recyclerView.setVisibility(View.VISIBLE);

                    aAdapter.notifyDataSetChanged();

            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Toast.makeText(Categories.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();

            }
        });

Firebase Json

{
  "MyStudents" : {
    "KihlyfLkJMQ5uZWBDgLWNuBHKAE2" : {
      "-MSr8HG6QCR2sO8MZHoM" : {
        "category" : "Football",
        "created" : "2-19-2021",
        "name" : "Benny",
        "time" : "2:47 AM",
        "timestamp" : 1613684875762
      },
      "-MSr8awtvzrmm3P6A2LB" : {
        "category" : "Basketball",
        "created" : "2-19-2021",
        "name" : "patrick",
        "time" : "2:49 AM",
        "timestamp" : 1613684960454,
      },
      "-MSr8mSn5OSTu5vdT4Wt" : {
        "category" : "Football",
        "created" : "2-19-2021",
        "name" : "Shawn",
        "time" : "2:50 AM",
        "timestamp" : 1613685007616,
      }

{
  "MyStudents" : {
    "WahlyfLkJMQ5uZWBDgLWNuBHKAE2" : {
      "-MSr8HG6QCR2sO8MZHoM" : {
        "category" : "Football",
        "created" : "2-19-2021",
        "name" : "Len",
        "time" : "2:47 AM",
        "timestamp" : 1613684875762
      },
      "JJr8awtvzrmm3P6A2LB" : {
        "category" : "Basketball",
        "created" : "2-19-2021",
        "name" : "Armstrong",
        "time" : "2:49 AM",
        "timestamp" : 1613684960454,
      },
      "-JJr8mSn5OSTu5vdT4Wt" : {
        "category" : "Football",
        "created" : "2-19-2021",
        "name" : "Bill",
        "time" : "2:50 AM",
        "timestamp" : 1613685007616,
      }

The problem in your code lies in the fact that you are using an incorrect query:

databaseReference.child("Sports").orderByChild("category").equalTo("football"))

Assuming that MyStudents is a child right under your root node and the following statement:

if (Categories.InternetConnection.checkConnection(Categories.this)) { /* ... */ }

Returns true , please use the following query:

String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child(uid);
Query queryByCategory = uidRef.orderByChild("category").equalTo("Football");
queryByCategory.addValueEventListener(/* ... */);

Things to notice:

  1. KihlyfLkJMQ5uZWBDgLWNuBHKAE2 is the UID of the logged-in user and should be added as a child in the reference.
  2. The value of the category property is called "Football" and not "football", with lower-case "f".

Edit:

According to your last comment:

I'm not trying to just get their information I'm trying to get everyone that has students whose category is Football

There is no way you can achieve that using your actual database structure. The most simple solution I can think of is to create a new node that contains all Model_Information objects, no matter the user is. This practice is called denormalization and is a common practice when it comes to Firebase. For a better understanding, I recommend you see this video, Denormalization is normal with the Firebase Database .

Also, when you are duplicating data, there is one thing that needs to keep in mind. In the same way, you are adding data, you need to maintain it. In other words, if you want to update/delete an item, you need to do it in every place that it exists.

Here is the answer. Hopefully its helpful for someone:)

    databaseReference = FirebaseDatabase.getInstance().getReference().child("MyStudents");
        if (Categories.InternetConnection.checkConnection(Categories.this)) {
    
            databaseReference.addValueEventListener(new ValueEventListener() {
    
    
                @Override
                public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
    
                        myUploads.clear();
    
                    for (DataSnapshot userSnapshot : dataSnapshot.getChildren()) {
                        for (DataSnapshot postsnapshot : userSnapshot.getChildren()) {
                            Model_Information upload = postsnapshot.getValue(Model_Information.class);
                         
                            Collections.shuffle(myUploads);
    
                                    if (upload.getCategory().equals("Football")) {
                                        myUploads.add(upload);
                                    }else{
                                       
   Toast.makeText(Categories.this, "No results", Toast.LENGTH_LONG).show();

    
                                    }
    
                                    recyclerView.invalidate();
                                }
                          
                            myUploads.add(upload);
                            recyclerView.invalidate();
                        }
                    }
                        
    
                        aAdapter.notifyDataSetChanged();
    
                }
    
                @Override
                public void onCancelled(@NonNull DatabaseError databaseError) {
                    Toast.makeText(Categories.this, databaseError.getMessage(), Toast.LENGTH_LONG).show();
    
                }
            });

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