16

I am trying to use Firebase in my android application. I am following documentation for Saving and retrieving, But the Sample database(Dragon) which is used in tutorial has different structure than my database.

This is my code for Pushing the data to firebase

Firebase myFirebaseRef = new Firebase("https://myfirebaseurl.firebaseio.com/android/saving-data/fireblog");
                User userName = new User(socialNum, name, datofBirth, mob1, mob2, healthCondition);
                Firebase usersRef = myFirebaseRef.child(name);
                Map<String, User> users = new HashMap<String, User>();
                users.put(name, userName);                    
              myFirebaseRef.push().setValue(users);

which create database format like this

{
      "android" : {
        "saving-data" : {
          "fireblog" : {
            "-JiRtkpIFLVFNgmNBpMj" : {
              "Name" : {
                "birthDate" : "100",
                "fullName" : "Name",
                "healthCond" : "fyhft",
                "mob1" : "5855",
                "mob2" : "5858",
                "socialNumber" : "100"
              }
            },
            "-JiRv0RmHwWVHSOiZXiN" : {
              "mast" : {
                "birthDate" : "100",
                "fullName" : "mast",
                "healthCond" : "fyhft",
                "mob1" : "5855",
                "mob2" : "5858",
                "socialNumber" : "100"
              }
            }
          }
        }
      }
    }

I want to Retrieve data from firebase such that, if I put "full Name" in my apps search box, it should retrieve that specific node, so that I can populate that information in Listview.

This is How I am trying to retrieve,

final String Find = find.getText().toString();   //Get text for search edit text box
                Firebase myFirebaseRef = new Firebase("https://myfirebaseurl.firebaseio.com/android/saving-data/fireblog");
                Query queryRef = myFirebaseRef.orderByChild("fullName");
               // System.out.println(dataSnapshot.getKey() + "is" + value.get("socialNumber"));
                System.out.println(Find);

                queryRef.addChildEventListener(new ChildEventListener() {
                    @Override
                    public void onChildAdded(DataSnapshot dataSnapshot, String previousChild) {
                        System.out.println(dataSnapshot.getValue());
                        Map<String,Object> value = (Map<String, Object>) dataSnapshot.getValue();

                        String name1 = String.valueOf(value.get("fullName"));
                    //System.out.println(dataSnapshot.getKey() + "is" + value.get("fullName").toString());
                    if (name1.equals(Find)){
                        System.out.println("Name" + value.get("fullName"));
                    }
                    else{
                        System.out.println("its is null");
                    }

                    }

but It returns all the nodes,

02-19 12:18:02.053    8269-8269/com.example.nilesh.firebasetest I/System.out﹕ name
02-19 12:18:05.426    8269-8269/com.example.nilesh.firebasetest I/System.out﹕ {Name={socialNumber=100, birthDate=100, fullName=Name, mob1=5855, mob2=5858, healthCond=fyhft}}
02-19 12:18:05.426    8269-8269/com.example.nilesh.firebasetest I/System.out﹕ its is null
02-19 12:18:05.426    8269-8269/com.example.nilesh.firebasetest I/System.out﹕ {mast={socialNumber=100, birthDate=100, fullName=mast, mob1=5855, mob2=5858, healthCond=fyhft}}
02-19 12:18:05.426    8269-8269/com.example.nilesh.firebasetest I/System.out﹕ its is null

How can i Retrieve specific node so that If I enter fullName = mast, it should retrieve only second node with all the fields in that node.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
gooner
  • 349
  • 1
  • 4
  • 17
  • 5
    It looks like there is a superfluous level of children. The data is structured as `saving-data/fireblog//fluff/...actual data...` and the `fluff` layer needs to be removed for those queries to work. You can't query children of children. – Kato Feb 20 '15 at 15:20
  • @Kato , Yes I noticed that and modified my Push code.The query works now. However now another problem I'm facing now in *If(Data not found )* condition. As this query goes through all the nodes one by one, I cant get my code in *else{} statement* to work. I considered using 'queryRef.addListenerForSingleValueEvent' but then query returns all the nodes – gooner Feb 22 '15 at 06:43
  • That sounds like an answer @kato. :-) – Frank van Puffelen Feb 22 '15 at 14:26
  • @FrankvanPuffelen feel free to add a note in your answer since that one will be referenced by anyone visiting the question. – Kato Feb 22 '15 at 14:53
  • @FrankvanPuffelen, I have question. Why does the same query (_Query queryRef = myFirebaseRef.orderByChild("fullName").equalTo("gooner");_) returns different results in _queryRef.addChildEventListener()_ and _queryRef.addListenerForSingleValueEvent()_ ? First one returns single specific node while second returns all the nodes. – gooner Feb 23 '15 at 07:04

4 Answers4

23

You're creating a query in this line:

Query queryRef = myFirebaseRef.orderByChild("fullName");

Like that the query orders the child nodes by their fullName value. But it doesn't yet limit what child nodes are returned.

To limit the nodes, you also have to filter. e.g.:

Query queryRef = myFirebaseRef.orderByChild("fullName").equalTo("gooner");

You can also get a range of nodes, by filtering with startAt and/or endAt instead of equalTo.

As Kato commented:

It looks like there is a superfluous level of children. The data is structured as saving-data/fireblog/<record id>/fluff/...actual data... and the fluff layer needs to be removed for those queries to work. You can't query children of children.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Thanks for responding. I am accepting your answer, However @Kato 's comment was much helpful for me. Can u also please help me understand difference between *queryRef.addListenerForSingleValueEvent()* and *queryRef.addChildEventListener()* with best use case scenario? – gooner Feb 22 '15 at 06:48
  • @gooner using the Query for SingleValueEvent will register a ValueEvent for that query one time and when the operation is done it will remove the listener automatically. The addChildEventListener, you register a ChildEventListener that will listen for changes in each one of the child nodes in the node you are querying – realdm Sep 08 '16 at 15:33
  • How to retrieve all the nodes who have certain value same. like all Houses with Blue paint – Abhi Mar 16 '18 at 09:11
2

If you want to get value of specif node or child node like this

enter image description here

Here if you want to get child node(address) value. You can get it in this way

    FirebaseDatabase database;
    DatabaseReference myRef;
    myRef = database.getReference();
    final DatabaseReference orders_Reference = myRef.child("Order");


 orders_Reference.addValueEventListener(new ValueEventListener() {
        @Override
        public void onDataChange(DataSnapshot dataSnapshot) {
            for (DataSnapshot data : dataSnapshot.getChildren()) {
                if(data.getKey().equals("address")){
                String orderNumber = data.getValue().toString();
                Log.d("Specific Node Value" , orderNumber);
               }
            }
        }
        @Override
        public void onCancelled(DatabaseError databaseError) {
        }
    });
Sheharyar Ejaz
  • 2,808
  • 1
  • 14
  • 15
1

This is another way to retrieve single value from firebase database using Hashmap.

     ArrayList<HashMap<String,String>> AllUserscourselist;
 String SelectedCourseUserUId;
     DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();

     databaseReference.child("User_course_Details").addValueEventListener(new ValueEventListener() {
                @Override
                public void onDataChange(DataSnapshot dataSnapshot) {
    //                        emergencyContactsList = new ArrayList<>();
                    AllUserscourselist = new ArrayList<HashMap<String, String>>();
                    if(dataSnapshot.exists())
                    {
                        for(DataSnapshot postSnapShot:dataSnapshot.getChildren())
                        {

                            for (DataSnapshot courseUID : postSnapShot.getChildren()){
                                UsercourseDetails usercourseDetails = courseUID.getValue(UsercourseDetails.class);
                                HashMap<String, String> map = new HashMap<String, String>();

                                String user_id = postSnapShot.getKey();
                                String course_id = usercourseDetails.getcourse_id();
                                String course_type = usercourseDetails.getcourse_type();
                                String course_brand = usercourseDetails.course_brand;
                                String course_number_plate_url = usercourseDetails.course_number_plate_url;

                                map.put("user_id", user_id);
                                map.put("course_id", course_id);
                                map.put("course_type", course_type);
                                map.put("course_brand", course_brand);
                                map.put("course_number_plate_url", course_number_plate_url);

                                AllUserscourselist.add(map);
                            }

    //                        AllUserscourselist.add(new UsercourseDetails(usercourseDetails.getcourse_type(),usercourseDetails.getcourse_brand(),usercourseDetails.getcourse_number_plate_url(),usercourseDetails.getcourse_id()));
                        }

                        Log.e("AllUserscourselist",""+AllUserscourselist);

                        courseIdList = new ArrayList<String>();
                        for (int i = 0; i < AllUserscourselist.size(); i++) {
                            String course_id_list;
                            course_id_list = AllUserscourselist.get(i).get("course_id")+" "+ AllUserscourselist.get(i).get("user_id");
                            courseIdList.add(course_id_list);
                        }

                        if(courseIdList.size()>0 && courseIdList!=null) {
                            for (int i = 0; i < courseIdList.size(); i++) {   //used
                                String arr[] = courseIdList.get(i).split(" ");
                                if (arr[0].equals(coursenumber)) {
                                    SelectedcourseUserUId = arr[1];
                                    getUserEmergencyContacts(SelectedcourseUserUId);
                                    break;
                                }
                            }
                        }

                    }else{
    //                    NavigationActivity.this.overridePendingTransition(R.anim.anim_slide_in_left, R.anim.anim_slide_in_left);
                    }
                }
                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
viral 9966
  • 515
  • 5
  • 16
0

Instead of getting all the nodes and then iterating it to get nodes based on value, just trigger the query provided by firebase.

   private void readAllRequestedFormFromFirebaseDb(){
    final FirebaseDatabase database = FirebaseDatabase.getInstance();
    DatabaseReference ref = database.getReference("App_DB");
    DatabaseReference childRef = ref.child("AllRequest");
    Query queryRef = 
  childRef.orderByChild("fullName").equalTo("Jay");
    queryRef.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot snapshot) {

            // getting list
            for(DataSnapshot dataSnapshot: snapshot.getChildren()){
                QueryFormModel post = dataSnapshot.getValue(QueryFormModel.class);
                queryFormModelArrayList.add(post);
                /*the above list will have record only
                 with the provided fullName as Jay*/

            }

        }
        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {
            Log.e("DetailsActivity", "onCancelled:readAllSubmittedRequestFromFirebaseDb:  "+databaseError );
        }
    });
}

Click here and find the beautifully written post about this topic

Amit
  • 72
  • 4