Anupam Singh
Anupam Singh

Reputation: 41

Firebase on Android : DataSnapshot.getChildrenCount() is returning 0

This is my firebase realtime database :

Firebase Databse

This is my code :

            DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference();
            EditText t1 = (EditText) findViewById(R.id.editText10);

            final String s1 = t1.getText().toString();

            mDatabase.child("users").orderByChild("name")
                    .equalTo(s1)
                    .addValueEventListener(new ValueEventListener() {
                        @Override
                        public void onDataChange(DataSnapshot dataSnapshot) {
                                    TextView tv2 = (TextView) findViewById(R.id.textView5);
                                    tv2.setText(Long.toString(dataSnapshot.getChildrenCount()));
                        }
                     }

I am entering these values in EditText fields :

            editText10 => Anupam Singh

dataSnapshot.getChildrenCount() should be 1 but it is coming to be 0.

What am I doing wrong?

Upvotes: 0

Views: 417

Answers (2)

Sachin Sah
Sachin Sah

Reputation: 1

-the issue is in orderByChild. -you have pass query and ask for single value event listener.

do as below :

DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users");

     Query query =  mDatabase.("name_title_company_location")
                .equalTo(s1 + "_" + s2 + "_" + s3 + "_" + s4);

                query.addSingleValueEventListener(new ValueEventListener(){
                    @Override
                    public void onDataChange(DataSnapshot dataSnapshot) {
                                TextView tv2 = (TextView) findViewById(R.id.textView5);
                                tv2.setText(Long.toString(dataSnapshot.getChildrenCount()));
                    }
                 }

-it will return the data

Upvotes: 0

Peter Haddad
Peter Haddad

Reputation: 80952

In your database you have the following:

users
    name_title_company_location

Therefore the attribute name_title_company_location is a direct child under nodeusers. When you are using orderByChild, you are not accessing that node.

What you need to do is add an id in the database:

users
    id
     name_title_company_location

Then your code will work.


Or you can change the code to the following, go one level up:

mDatabase.orderByChild("name_title_company_location").equalTo(...)

Upvotes: 1

Related Questions