Home » Android » android – Firebase realtime database cannot query with integer-Exceptionshub

android – Firebase realtime database cannot query with integer-Exceptionshub

Posted by: admin February 26, 2020 Leave a comment

Questions:

I have sample of data like below

{
  "random_key 1" : {
    "id": 0,
    "text": "This is text"
  },
  "random_key 2" : {
    "id": 1,
    "text": "This is text"
  }
}

I want to Query to get the node with ‘id’ equal to 1.

val database = FirebaseDatabase.getInstance().getReference()
database.orderByChild("id").equalTo(1)

But this code return error because follow google document by this link: https://firebase.google.com/docs/reference/android/com/google/firebase/database/Query

The library is only support for Double, Boolean and String. I am really confuse now. How it possible?

How to&Answers:

Yes, You are right.

The library is only support for Double, Boolean and String.

Also your query is right. As firebase consider 1 as double. So, your query should work. Check below:

DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference();
Query query = databaseReference.orderByChild("id").equalTo(1);
query.addListenerForSingleValueEvent(new ValueEventListener() {
    @Override
    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
        for(DataSnapshot childSnapshot: dataSnapshot.getChildren()) {

            String textValue = childSnapshot.child("text").getValue(String.class);

        }
    }

    @Override
    public void onCancelled(@NonNull DatabaseError databaseError) {

    }
});

Update for Kotlin: In Jave, int to double is automatically convert using assignment operator as lower type can be converted to higher type implicitly. This is also known as implicit type casting or type promotion.

But in Kotlin, there is nothing about implicit type casting. You have to do it yourself using toDouble(). Check below:

val databaseReference = FirebaseDatabase.getInstance().reference
val query = databaseReference.orderByChild("id").equalTo(1.toDouble())
query.addListenerForSingleValueEvent(object: ValueEventListener {
    override fun onCancelled(dataSnapshot: DatabaseError) {
        TODO("not implemented") //To change body of created functions use File | Settings | File Templates.
    }

    override fun onDataChange(dataSnapshot: DataSnapshot) {
        dataSnapshot.children.forEach { childSnapshot-> 

            val textValue = childSnapshot.child("text").getValue(String::class.java)
        }
    }
})