0

I'm making an app and I need to match data continuously in the activity. I'm using firebase for the database and I'm getting problem of getting my query right. I want to match the data in child(uid) to other data in different child(uid), in this case I'm still testing with only the date.

EDIT: I need to match the child of uid1 (for this case, the date) to ALL EXISTING dates available in the "Schedules". My bad.. the previous question stated was wrong where i said "matching the uid1 data to uid2 data"

This  is the database tree

Here is my code. I think my conditions aren't correct.

 mInstance.getReference("Schedules").addValueEventListener(new ValueEventListener(){
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            Schedule schedule = dataSnapshot.child(uid).getValue(Schedule.class);


                for(DataSnapshot data: dataSnapshot.getChildren()) {
                    if (dataSnapshot.child(uid).child("date").exists() && dataSnapshot.child(uid).child("date").getChildrenCount()>= 2) {
                        test.setText("Found Match for " + schedule.date + "," + schedule.sport + ", and " + schedule.location);
                    } else {
                        test.setText(schedule.date + schedule.sport + schedule.location);
                    }

                }

        }
        public void onCancelled(DatabaseError error) {
            // Failed to read value
            Log.w(TAG, "Failed to read value.", error.toException());
        }

2 Answers2

0

Looking at your database cant a child("date") with children count greater than two. If i may ask why are doing this?

There are two different approach to solve this problem

  1. Get a list<> of all schedules from database and simply compare uid

    or

  2. If you already know the uid of the data you are looking for, get the data from database

More on firebase query

    private Query queryGetSchedule;
    private Query queryAllSchedule;
    private ValueEventListener schedulesListener;
    private ValueEventListener allSchedulesListener;
    private FirebaseDatabase;

    //Inside onCreate or class your are using
    this.context = context; //pass in context 
    this.app = FirebaseApp.initializeApp(context);
    this.id = myid;
    if(firebaseDatabase == null) firebaseDatabase = FirebaseDatabase.getInstance();

    queryGetSchedule = firebaseDatabase.getReference("Schedules").Child("key");
    queryAllSchedule = firebaseDatabase.getReference().child("Schedules");



      /**
     * This will get you a single schedule
     */
    public void getSingleSchedules()
    {
        if(schedulesListener == null)
        {
            schedulesListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    // Get Post object and use the values to update the UI

                    if (dataSnapshot.exists()) {
                        for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
                           // MainActivity.userBook = snapshot.getValue(UserBook.class);
                            Schedule schedule = snapshot.getValue(Schedule.class);
                            callback.onUserCallback(userBook);
                        }
                    }

                }


                @Override
                public void onCancelled(DatabaseError databaseError) {
                    // Getting Post failed, log a message

                }
            };
        }
        queryGetSchedule.addListenerForSingleValueEvent(schedulesListener);
    }



    /**
    *This will get you all your schedules in a list so you can easily compare
    * Let assume you are passing in schedule of interest into this method
    */
    public void getAllSchedulesListener(Schedule scheduleOfInterest) {

        if(allSchedulesListener == null) {
            allSchedulesListener = new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
                    // Get Post object and use the values to update the UI

                    //Use this for list of objects passing in the type
                    GenericTypeIndicator<List<Schedule>> schedulesList = 
                    new GenericTypeIndicator<List<Schedule>>() {
                    };

                    if(dataSnapshot.exists()) {

                       List<Schedule> mySchedulesList = dataSnapshot.getValue(schedulesList);

                       //after you get this full list of schedule you can compare with date as a string 
                        for(Schedule schedule: mySchedulesList)
                        {
                            if(scheduleOfInterest.date.equals(schedule.date)
                            {
                                //found it 
                                //do whatever here
                            }
                        }

                    }
                }

                @Override
                public void onCancelled(DatabaseError databaseError) {
                    // Getting Post failed, log a message
                }
            };
        }
      queryAllSchedule.addListenerForSingleValueEvent(allSchedulesListener);
    }
0

To solve this, simply use the following lines of code:

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidOneRef = rootRef.child("Schedules").child(uidOne);
ValueEventListener valueEventListener = new ValueEventListener() {
    @Override
    public void onDataChange(DataSnapshot dataSnapshot) {
        String dateOne = ds.child("date").getValue(String.class);

        Query uidTwoRef = rootRef.child("Schedules").orderByChild("date").equalTo(dateOne);
        ValueEventListener eventListener = new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                String dateTwo = ds.child("date").getValue(String.class);
                Schedule schedule = dataSnapshot.getValue(Schedule.class);

                if(dateOne.equals(dateTwo)) {
                    test.setText("Found Match for " + schedule.date + "," + schedule.sport + ", and " + schedule.location);
                } else {
                    test.setText(schedule.date + schedule.sport + schedule.location);
                }
            }

            @Override
            public void onCancelled(@NonNull DatabaseError databaseError) {
                Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
            }
        };
        uidTwoRef.addListenerForSingleValueEvent(eventListener);
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {
        Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
    }
};
uidOneRef.addListenerForSingleValueEvent(valueEventListener);

In which uidOne and uidTwo are the id of the users you want to check. I highly recommend you to store the data as a timestamp and not as a String, as it is explained here.

Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Hi, I think I made a wrong explanation, i want the code to be dynamic, so I can compare the date (let's say date1) with EVERY date available in the "Schedules". – Michael Wijaya Dec 09 '18 at 12:34
  • In this case please see my updated answer. Does it work? – Alex Mamo Dec 09 '18 at 12:50
  • Thanks for your help, but unfortunately it still didn't work. I got an error in this line: DatabaseReference uidTwoRef = rootRef.child("Schedules").orderByChild("date").equalTo(dateOne); It says that this is a Query type, and cannot go into the DatabaseReference type. I tried to tweak it but still doesn't work. – Michael Wijaya Dec 10 '18 at 07:18
  • Yes, you're right. It should be `Qyery` and not `DatabaseReference.` Please see my updated answer. Does it work now? – Alex Mamo Dec 10 '18 at 07:20
  • It is successfully compiled, but it gives me null value on this: test.setText(schedule.date + schedule.sport + schedule.location); I think the reference to the database is not correct, I'm currently still working on it. – Michael Wijaya Dec 10 '18 at 07:52
  • There is no error, but it returns null value.https://imgur.com/a/AQn1Cl6 – Michael Wijaya Dec 10 '18 at 08:00
  • If you are trying to `Log.d(TAG, dateTwo);` what is the output? – Alex Mamo Dec 10 '18 at 08:11
  • What if using `Log.d(TAG, dateOne);`? – Alex Mamo Dec 10 '18 at 08:18
  • It showed `2018-12-10 15:20:24.977 11249-11249/com.sparingan D/MainMenu: 9/12/2018`. So the dateOne is correct. But the dateTwo is null. – Michael Wijaya Dec 10 '18 at 08:26