Firebase search by child value KOTLIN - firebase

This is my firebase realtime database structure
I want to retrieve all questions with QID = "PQ1" . What i tried is given below . Its result is null .
database.child("Question").child("QID").equalTo("PQ1").limitToFirst(200).get().addOnSuccessListener {
Log.i("12345", "Got value ${it.value}")
}
My references :
Firebase - Search a child by value
Firebase search by child value
Search firebase by Child of child value

Your call to database.child("Question").child("QID") looks for a child node at path /Question/QID in your database, which doesn't exist and thus explains why you get an empty snapshot.
To query the Firebase Realtime Database needs two steps:
You order all child nodes on a property, on their key, or on their value by calling on of the orderBy... methods.
You then filter the ordered child nodes by calling one or more of the equalTo, startAt, startAfter, endAt, endBefore, limitToFirst and/or limitToLast methods.
While you're doing #2, you're not ordering the nodes first by calling orderBy....
The correct code:
database.child("Question").orderByChild("QID").equalTo("PQ1").limitToFirst(200).get().addOnSuccessListener {
Log.i("12345", "Got value ${it.value}")
}
Also don't forget that executing a query will potentially have multiple results, so the snapshot in it.value contains a list of those results and you will need to iterate over its children. Even if there is only a single result, the snapshot will contain a list of one result.

Related

Is there a way to retrieve realtime firebase map as a linkedhashmap or at least maintain the order it is saved in

I have a map of string boolean pairs saved on firebase realtime database and was wondering if there is a way to retrieve it in kotlin as a linkedhashmap such that the original order remains in place.
I have tried typecasting to a linkedhashmap and got an error that hashmap cannot be typecasted to linked hashmap, I then tried calling the linkedhashmap constructor method with the parameter being the data from the database as a hashmap but that does not maintain the order
Properties in JSON are by definition not in any specific order.
While you can retrieve data from Firebase in a specific order, by calling one of its orderBy... operations, that order will be lost when you call .value in the DataSnapshot as DataSnapshot.value returns a Map, which is unordered again.
If you want to retrieve the nodes in a specific order:
Call orderBy... to get the nodes in a specific order.
Loop over the children of the snapshot you get back to process them in order, and only call value on each specific child node.

kotlin firebase remove child

I'm trying to delete a specific value from a firebase realtime database, but I don't know how to do it because I don't know to save or find the key value of the child which is automatically generate.
If you see the picture I've only managed to remove all the children from the first key with
FirebaseDatabase.getInstance().reference.child("Comentarios").removeValue()
But I need to delete just by the child creadoPor
Is there any way of skkiping an unnamed child?
FirebaseDatabase.getInstance().reference.child("Comentarios").removeValue()
But I need to delete just by the child creadoPor.
Since you know the "grantparent" key of the data and the value of one of the nodes properties, you can use a query to find the nodes that match that value.
FirebaseDatabase.instance
.ref("Comentarios")
.child("-NGi7xP...")
.orderByChild("creadoPor")
.equalTo("R7lji3...")
When you get the DataSnapshot from the query, you'll need to loop over its children as shown in the documentation on listening for value events. Even when there's only one result, you'll get a list of one child node and thus will need to loop over them.

Index error in query in Firebase

I'm having trouble setting up a search query within my Firebase database. I put the rules all the way of my search, but I always get the index error.
Below is my structure:
My Firebase database structure:
My query:
https://zoome-production-users.firebaseio.com/country.json?orderBy="fullname"&equalTo="Vitor Darela"
Erro:
{
"error": "Index not defined, add \".indexOn\": \"fullname\", for path \"/country\", to the rules"
}
In your REST call, you run a query on /country in your database. This query inspects each direct child node of /country to see if it matches your filter. In your JSON data /country/AD does not have a property fullname, so the query will not return anything. Even if you were to add the index that the error message tells you about, it will not return anything.
The query you are trying to do is not possible with your current data structure. You will need to modify your data structure to allow it. It seems that you're trying to to find the countries that have a user with a certain name. To allow that query, add an additional data structure that holds precisely that:
"countries_by_fullname": {
"Vitor Darela": {
"AD": true
}
}
With this additional structure you can find the list of countries by simply reading /countries_by_fullname/Vitor Darela.
Also see:
Firebase Query Double Nested
Firebase query if child of child contains a value

Firebase OrderByChild return extra empty child

I'm trying to make query with orderBy and I get another empty child.
component .ts
loadCourses(){
this.profileProvider.getSpecificCourse().on('value',f=>{
console.log(f.val());
})
}
provider
getSpecificCourse(){
return firebase.database().ref(`CoursesRelated`).orderByChild('cs').equalTo(2);
}
firebase structure
getting the another empty node
expected result:
the same result without the empty node.
in addition I want to make another orderby and get the ls equal to 6, how can I do that?
You're using numeric indexes to store the nodes, which means that Firebase SDK interprets them as an array. For the results: { "0": {...}, "2": {...} it then creates a three element array [{...}, null, {...}].
For a good, longer explanation of how Firebase deals with arrays, read this blog post Best Practices: Arrays in Firebase.
The way to get rid of this behavior is to not use sequential numeric keys. The simplest way to do this is to either add the items by calling Firebase's push() method (which generates keys in a format -K... and is explained here), or by prefixing the numbers with a fixed string (e.g. Course0, Course1, Course2). Since these format are strings, they bypass the Firebase SDK's array-coercion logic.

In Firebase whats the difference between push and childByAutoId

In Firebase if I'd like to create a child node with a unique ID it appears I have two options:
Push() :
Use the push() method to append data to a list in multiuser
applications. The push() method generates a unique ID every time a new
child is added to the specified Firebase reference. By using these
auto-generated keys for each new element in the list, several clients
can add children to the same location at the same time without write
conflicts. The unique ID generated by push() is based on a timestamp,
so list items are automatically ordered chronologically.
childByAutoId:
childByAutoId generates a new child location using a unique key and
returns a FIRDatabaseReference to it. This is useful when the children
of a Firebase Database location represent a list of items. The unique
key generated by childByAutoId: is prefixed with a client-generated
timestamp so that the resulting list will be chronologically-sorted.
Whats the difference?
Nevermind, it appears they are the same except they cater to different platforms:
Save Data on IOS
childByAutoId : Add to a list of data. Every time you call childByAutoId, Firebase generates a unique ID, such as user-posts/<user-id>/<unique-post-id>.
Save Data on Web
push() : Add to a list of data. Every time you call push(), Firebase generates a unique ID, such as user-posts/<user-id>/<unique-post-id>.

Resources