How to apply multiple query in android firebase? [duplicate] - android

This question already has answers here:
Query based on multiple where clauses in Firebase
(8 answers)
Closed 6 years ago.
This is My Firebase database structure
i want to get data like
category = "cat" and level = "1"
Here is my code
Query query = firebaseReference.orderByChild("category").equalTo("cat1").limitToFirst(20);
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UTILS.Log.e(TAG, "List Of User Count " + dataSnapshot.getChildrenCount());
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
//FCreateUSer modelRegister = dataSnapshot1.getValue(FCreateUSer.class);
UTILS.Log.e(TAG, "User Email :" + dataSnapshot1.child("question").getValue());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
it's wrok but how to use two condition in firbase i try two orderByChild but it's give error java.lang.IllegalArgumentException: You can't combine multiple orderBy calls!

Take a look at this video (it's in JavaScript, but it exactly solves your problem): https://youtu.be/sKFLI5FOOHs?t=612
Basically, you need to structure your data for your queries. In OP example Question will have field like category_level: "cat_1". Then you can perform query equalTo("cat_1"). You can leave out both category and level fields if you need it for other queries (but you will need to handle duplication in that case).
If you know that your number of items is small, simplest solution is to just pull all category=cat and filter level=1 items.

Related

Retrieve data from multiple push ids under a single child in firebase realtime database

I am new to android studio and programming and am currently trying to make my first app. In firebase RTDB, I have multiple push ids under a single child that keep on increasing in number as the user presses certain buttons, and they all store only an integer. I want to retrieve the data from all those push ids(or keys, I don't really know what they are actually called) under the child and then sum the integers up and display the result in a textView and do it every time a new field is added. How can I do that? So far I only know how to normally send and receive data to childs sub-childs like this but i have never ever used push ids or keys before:
String recieve = datasnapshot.child("Child").child("subchild").getText().toString();
String send = "send";
databaseReferenc.child("Child").child("sunchile").setValue(send);
The data tree in firebase is as follows:
Assuming that Australia is a direct child of your Firebase Realtime Database root, to sum all those values, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference australiaRef = rootRef.child("Australia");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
int total = 0;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String value = Integer.parseInt(ds.getValue(String.class));
total += value;
}
Log.d("TAG", "total: " + total);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
australiaRef.addListenerForSingleValueEvent(valueEventListener);
One more thing. Because you are storing numbers, it best to store them as long values and not as String values.

Android ignore Case sensitive with Firebase whereEqualTo [duplicate]

This question already has answers here:
Cloud Firestore Case Insensitive Sorting Using Query
(3 answers)
Closed 4 years ago.
db.collection("UserInformation").whereEqualTo("userName" , searchEditText.getText().toString())
.get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#Override
public void onSuccess(final QuerySnapshot documentSnapshots) {
if (documentSnapshots.isEmpty())
{
}else
{
List<UserModel> listUsers = documentSnapshots.toObjects(UserModel.class);
final SearchUserListAdapter adapter = new SearchUserListAdapter(getBaseContext() , listUsers);
searchLista.setAdapter(adapter);
}
}
});
i need to ignore case sensitive and find the "nickname" however i typed the nickname with capital or small letters or both i tried to add startAt() or endAt() and i didn't worked for me and the all answers talk about to save the nickname with upper and lower case but it is not good logic to me
I think there is no support for lowercase searches in Firebase. An idea to handle this would be to store the lowercase string along side the original string and then query the lowercase string instead.

How to search anywhere in string in Firebase Database - Android

I have implemented firebase realtime database in my android app, everything is fine. I am trying to add a a search function and I am able to search the database with only starting word match.
Below is my database snapshot:
I am querying for movieName. Right now I am able to search if the query string is Pets/Pe/pet. But when I search for Animals, I get zero results. So, basically what I am looking for is searching the database with query text anywhere in the string. ie., I should be able to search Animals/and/pets and should get the results which contain the search query.
Below is my code so far.
mDatabaseReference.child("recent").getRef().orderByChild("movieName").startAt(query)
.endAt(query + "\uf8ff")
To seach for a string within a String please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference animalsRef = rootRef.child("Animals");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Boolean found;
String search = "Animals";
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String movieName = ds.child("movieName").getValue(String.class);
found = movieName.contains(search);
Log.d("TAG", movieName + " / " + found);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
animalsRef.addListenerForSingleValueEvent(eventListener);
As you see, we query the database for all the movie names and then search for the desired word within the movieName.
First of all check the exact child and initialize the Firebase as like. Have a look at this answer,
https://stackoverflow.com/a/34537728/5746625

How to query highest values if children have dynamic keys in Firebase? [duplicate]

My Firebase Database is like this
When the coding below was run:
String loc=(snapshot.child("loc").getvalue()).tostring();
The output I get has different sequence with the database:
Why is that so?
Firebase data is stored as JSON and is inherently unordered.
If you want to access the data in a specific order, you should specify an orderBy clause for your query and access the data using the snapshot's getChildren() method.
Say you want to log the items by ascending key:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getRef();
Query locations = rootRef.orderByKey();
locations.addListenerForSingleValueEvent(new ValueEventListener() {
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot locSnapshot: snapshot.getChildren()) {
System.out.println(locSnapshot.getKey() + ": " + locSnapshot.getValue(String.class));
}
}
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
// ...
}
});
This sample comes (modified) from the Firebase documentation on reading lists of data.
Frank beat me to my edit, check out his correct solution using orderBy....
You need to use forEach rather than the child method (or child.foreach)
Here is a snippet from the doc:
Because of the way JavaScript Objects work, the ordering of data in
the JavaScript Object returned by val() is not guaranteed to match the
ordering on the server nor the ordering of child_added events. That is
where forEach() comes in handy. It guarantees the children of a
DataSnapshot will be iterated in their query-order.
Source: https://firebase.google.com/docs/reference/js/firebase.database.DataSnapshot#forEach

Retrieving data in alphabetical order using Firebase in Android Studio [duplicate]

This question already has answers here:
How can I sort an ArrayList of Strings in Java?
(5 answers)
Closed 7 years ago.
This question is a follow up question from a previous post.
Is there anyway to order the results alphabetically? I'm looking for something like Query's orderByValue().
...
protected ArrayList<String> usernames = new ArrayList<>();
Firebase userRef = ref.child("users");
userRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
usernames.clear(); // Clear list before updating
for (DataSnapshot child : dataSnapshot.getChildren()) {
String username = (String) child.child("username").getValue();
usernames.add(username);
Log.v(TAG, usernames + "");
}
...
I believe you want Collections.sort(usernames) once you've read all of the children from the dataSnapshot.
How can I sort an ArrayList of Strings in Java?

Categories

Resources