1

This is my firebase database json:

{
  "trucks" : {
    "-KvLTRmYdJKuYKZfila6" : {
      "busiHours" : "월~금 09:00-22:00 강남역",
      "imgUrl" : "https://firebasestorage.googleapis.com/v0/b/movetodiner.appspot.com/o/trk11.png?alt=media&token=7971b439-7321-4496-bf7d-2564fa799f53",
      "starCount" : 1,
      "stars" : {
        "FJB7BWTdlyfCdzXJN4pwmSQWa1E3" : true
      },
      "truckDes" : "즉석 츄러스 전문점",
      "truckName" : "스윗 츄러스",
      "truckNo" : "1"
    },
    "-KvLTo5_eWVWxSAhemK4" : {
      "busiHours" : "월~일 09:00-19:00 홍대입구역",
      "imgUrl" : "https://firebasestorage.googleapis.com/v0/b/movetodiner.appspot.com/o/trk11.png?alt=media&token=7971b439-7321-4496-bf7d-2564fa799f53",
      "starCount" : 1,
      "stars" : {
        "FJB7BWTdlyfCdzXJN4pwmSQWa1E3" : true
      },
      "truckDes" : "수제 케밥을 알고싶니?",
      "truckName" : "오빠 손맛",
      "truckNo" : "2"
    },
    "-KvLTxrGs9tAs3w5jJVV" : {
      "busiHours" : "화, 목, 토,일 10:00-23:00 이태원",
      "imgUrl" : "https://firebasestorage.googleapis.com/v0/b/movetodiner.appspot.com/o/trk11.png?alt=media&token=7971b439-7321-4496-bf7d-2564fa799f53",
      "starCount" : 0,
      "truckDes" : "백종원이 추천한다!",
      "truckName" : "도깨비 핫도그",
      "truckNo" : "3"
    },
    "-KvLU4ViXM78aH_thFjF" : {
      "busiHours" : "ggg",
      "imgUrl" : "https://firebasestorage.googleapis.com/v0/b/movetodiner.appspot.com/o/trk11.png?alt=media&token=7971b439-7321-4496-bf7d-2564fa799f53",
      "starCount" : 2,
      "stars" : {
        "FJB7BWTdlyfCdzXJN4pwmSQWa1E3" : true,
        "Jm7JQQBGtzQgLUBgcEutB3O6YAV2" : true
      },
      "truckDes" : "6~7",
      "truckName" : "nonono",
      "truckNo" : "4"
    },
    "-KvLUCR-pBjQot6R1Cj6" : {
      "busiHours" : "TT",
      "imgUrl" : "https://firebasestorage.googleapis.com/v0/b/movetodiner.appspot.com/o/trk11.png?alt=media&token=7971b439-7321-4496-bf7d-2564fa799f53",
      "starCount" : 0,
      "truckDes" : "8~10",
      "truckName" : "Twice",
      "truckNo" : "5"
    }
  }
}

I want to retreive favorite List.

Query : Select * from trucks where stars (contains) FJB7BWTD~~;

F7B7 is my uid.

It will generate uid in starsfield if users click the favorite button.

So i want to check my uid in stars at every object.

So i thought it needs a query.

But it is not working.

enter code here
    Query mQuery=database.getReference().child("trucks").orderByChild("stars").equalTo(auth.getCurrentUser().getUid());
    mQuery.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot postSnapshot : dataSnapshot.getChildren())
            {
                favlist.add(postSnapshot.getValue().toString());
                System.out.println(postSnapshot.getKey() + " / " +postSnapshot.getValue().toString() + " / ");
            }
        }

        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });

Program skiped the my code.....;;

How to write code? Let me explain exatly.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Look the My screenshot image at above – 세실리아 Oct 02 '17 at 00:24
  • You've included a link to a picture of the JSON tree in your question. Please replace that with the actual JSON as text, which you can easily get by clicking the Export JSON link in [your Firebase Database console](https://console.firebase.google.com/project/_/database/data/). Having the JSON as text makes it searchable, allows us to easily use it to test with your actual data and use it in our answer and in general is just a Good Thing to do. – Frank van Puffelen Oct 02 '17 at 00:32
  • thank u, i added the link (json fille) – 세실리아 Oct 02 '17 at 01:18
  • This looks like a categorization problem. While it is technically possible to write that query, you'll need to define an index for each category - which is unfeasible. For more see my answer here: http://stackoverflow.com/questions/40656589/firebase-query-if-child-of-child-contains-a-value – Frank van Puffelen Oct 02 '17 at 02:54

1 Answers1

3

To achieve what you want, you need to change your database structure a little bit by adding a new node named favoriteList. You need to do in this way because there is no need to download the entire trucks object in order to query the database for favorite trucks. So your database structure should look like this:

Firebase-root
    |
    --- favoriteList
            |
            --- FJB7BWTdlyfCdzXJN4pwmSQWa1E3
            |      |
            |      --- -KvLTRmYdJKuYKZfila6: true
            |      |
            |      --- -KvLTo5_eWVWxSAhemK4: true
            |      |
            |      --- -KvLU4ViXM78aH_thFjF: true
            |
            --- Jm7JQQBGtzQgLUBgcEutB3O6YAV2
                   |
                   --- -KvLU4ViXM78aH_thFjF: true

In this way you can simply your query your database for all favorites trucks that belong to a single user by attaching a listener on Firebase-root -> favoriteList -> userId

When you create a new track, you are already using the push() method. So when you generate that key (i.e. -KvLTRmYdJKuYKZfila6 as i see at the first truck) just save that key to a variable like this:

String truckKey = yourRef.push().getKey();

To save data, please use the following code

DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userIdRef = rootRef.child("favoriteList").child("FJB7BWTdlyfCdzXJN4pwmSQWa1E3").child(truckKey).setValue(true);
Alex Mamo
  • 130,605
  • 17
  • 163
  • 193
  • Then how to save that data? that saving should not have push() method. right? and If User click the fav button then it need to save both star count in trucks node And Truck Keys in favoriteList node. – 세실리아 Oct 02 '17 at 12:39
  • No. You can use `push()` method to save those favorites as described above. – Alex Mamo Oct 02 '17 at 12:41
  • Let me explain exactly plz. i am beginner, So Write a sample. – 세실리아 Oct 02 '17 at 12:43