Firebase数据配对

时间:2018-12-03 06:08:27

标签: java android firebase firebase-realtime-database

我正在制作一个应用程序,我需要在活动中连续匹配数据。我正在将Firebase用于数据库,但遇到了无法正确查询的问题。我想将child(uid)中的数据与其他child(uid)中的其他数据进行匹配,在这种情况下,我仍然仅使用日期进行测试。

编辑:我需要将uid1的子项(在这种情况下为日期)与“计划”中可用的所有现有日期进行匹配。我的糟糕。.前面的问题是错误的,我说“将uid1数据与uid2数据匹配”

This  is the database tree

这是我的代码。我认为我的条件不正确。

 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 个答案:

答案 0 :(得分:0)

查看您的数据库无法找到一个孩子(“日期”),其孩子数大于两个。 如果我可以问为什么这样做?

有两种方法可以解决此问题

  1. 从数据库中获取所有日程表的列表<>,只需比较uid

  2. 如果您已经知道要查找的数据的uid,请从数据库中获取数据

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

答案 1 :(得分:0)

要解决此问题,只需使用以下代码行:

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

其中uidOneuidTwo是您要检查的用户的ID。我强烈建议您将数据存储为timestamp而不是字符串,如 here 所述。