15
votes

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.

3
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. - Kato
@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
That sounds like an answer @kato. :-) - Frank van Puffelen
@FrankvanPuffelen feel free to add a note in your answer since that one will be referenced by anyone visiting the question. - Kato
@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

3 Answers

23
votes

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.

2
votes

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) {
        }
    });
1
votes

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

                }
            });