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
Related
Please help
this is my firebase structure
firebase structure
following query is working fine but i have to hardcode the push id "MZgPRv6xKK5isnnPTLn" , i dont want to hard code the value highlighted below from following query is there a way to get this reference of this push key ? to be used for query so that i can replace the "MZgPRv6xKK5isnnPTLn"
push id hard coded
Query lastQuery = dbr1.child("users").child(mAuth.getCurrentUser().getUid())
.child("-MZgPRv6xKK5isnnPTLn").child("sms").orderByKey().limitToLast(1);
lastQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dns) {
for (DataSnapshot chl : dns.getChildren())
{
Log.d("read_last_nodes", String.valueOf(dns.child("no").getValue()));
}
}
}
Follows is the code of writing into Firebase
path= dbref_1.child("users").child(mAuth.getUid()).push().getKey();
dbref_1.child("users").child(mAuth.getCurrentUser().getUid()).child(path)
.child("sms").child("SMS_no_" + i).child("no").setValue(no);
You can use 'getKey()' to get any key in firebase database. In your case to get the key you have to point to the hardcoded key, and then use getKey on the returned snapshot. After getting the key you can proceed to run your query.
DatabaseReference ref = dbr1.child("users").child(mAuth.getCurrentUser().getUid())
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dns) {
if(dns.exists) {
String key = dns.getKey();
Query lastQuery = dns.child(key).child("sms").orderByKey().limitToLast(1);
///rest of query logic
}
}
}
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.
I'm trying to build a user to user chat application, but I'm not able to order the chat list by last message sent.
My Firebase (real time) structure is like this:
I'm trying to retrieve the data like this, but i'm not able to order by "timestamp" in the inner message.
final String uID = firebaseAuth.getCurrentUser().getUid();
Query ref = FirebaseDatabase.getInstance().getReference("Messages");
ref.orderByChild("timestamp").startAt(uID).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
Did anyone knows how can I order the list of users by the timestamp of the last message?
You need to change the query to the following:
final String uID = firebaseAuth.getCurrentUser().getUid();
Query ref = FirebaseDatabase.getInstance().getReference("Messages");
ref.child(uID_uID).orderByChild("timestamp").addValueEventListener(new ValueEventListener() {
You need access to the direct node under the node Messages, the node with underscore. Then you can add orderByChild("timestamp").equalTo("157644739279")
I've been trying to figure out how to add data to my firebase real time database using Lists or ArrayLists.
For example I want to create a list of users who have liked a post and add them in a list/arraylist then upload that list/ArrayLists in my real time database.
After that I also want to retrieve the data from firebase.
To achieve this please use the following code:
List<String> friends = new ArrayList<>();
friends.add("John");
friends.add("Steve");
friends.add("Anna");
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
for(String friend : friends) {
rootRef.child("friends").child(friend).setValue(true);
}
Your database will look like this:
Firebase-root
|
--- friends
|
--- John: true
|
--- Steve: true
|
--- Anna: true
To get all those names into a List, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference friendsRef = rootRef.child("friends");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> friends = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String friend = ds.getKey();
friends.add(friend);
}
Log.d("TAG", friends);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
friendsRef.addListenerForSingleValueEvent(eventListener);
Your output will be:
[John, Steve, Anna]
I just make clarification. Do you want to manually add user list that liked post? This seems odd for me generally users individually liking post then update post like rate with users id whose like that post in server After you show it for user who display that post. Here some documents for read and write operation in firebase link
I want to use user location to Query some Country class
I want to put like this
Query query = database.child ("Countries").child ("received user location");
My database looks like
User--
|--- username David
|--- UserLocation florida
|--- userid jdjdkdkdidjdndjdidj
How to put UserLocation value inside the query
If you have already stored in your database the useerName or the userId, than you can query to find out the location of a particular user and than use it in your Query or DatabaseReference.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("users").child(userId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String userLocation = (String) dataSnapshot.child("location").getValue();
Query query = database.child("Countries").child(userLocation); //Do whatever you want with the query
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(eventListener);
Hope it helps.
The query is in another class so can we do like
Query location = mdatabase.child ("users").child (userid).equalTo ("UserLocation");
Then placing it on Query query = mdatabase.child ("countries").child (String.valueOf (location));
Because the query is in outer class and every time I try to use it it shows null pointer exception