How to get a child's data when it has been pushed? - java

I am using the "push()" function to store objects into my firebase database and since it stores data with unique keys I can't change the stored objects values using what's mentionned in the documentation:
myRef.child("child name").setValue(model);
because I simply don't know the key. I wan wondering is there an other way to modify the data of firebase database.
I want to add a new child called "conversations" to the users and programmatically add childs to him .
and this is the databse structure:

If you have the following database:
Users
pushId
name : john
age : 100
In case you dont know the pushId, you can do the following:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("Users");
databaseReference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()){
String key = ds.getKey();
String name = ds.child("name").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The above will get you the name and the key using getKey()

Related

dataSnapShot.getChildren() returning null

I'm trying to fetch the user details of a particular user using a query:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
Query query = reference
.child("user_account_settings"))
.orderByChild("user_id")
.equalTo(getItem(position).getUser_id());
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG, "onDataChange: the fetched user id is " + getItem(position).getUser_id());
for(DataSnapshot singleSnapshot : dataSnapshot.getChildren()){
//do stuff
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Firebase database screenshot
The user id that is fetched is correct according to the database and it clearly has children, but for some reason dataSnapshot.getChildren() is empty thus not allowing me to iterate through the foreach loop.
The problem in your code lies in the fact that the user ID property is called in the database userid, while in your query you are using user_id, which is incorrect. The name of the field in your query must match the name field in the database. To solve this, simply change:
.orderByChild("user_id")
To:
.orderByChild("userid")

How to parse all child fields and find what I need in Firebase Database?

I do password recovery and I need to know if there is a user in the database with the entered E-mail'om. How do I do that? Here is the structure:
For example, the user entered E-mail - goshan164#gmail.com and I need to know if there is such a mail in my database. And if it exists, then find out the uID of the user with such mail. How do I do that?
P.S uId initially I do not know. In the picture uId = zKCTYc1JkROrGxgOZgvm9CvfSU42
You're looking for a Firebase database query, in this case one that compares the child property of each node against the value you're looking for:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("users"); // or whatever your node is
Query query = ref.orderByChild("account").equalTo("goshan164#gmail.com");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot userSnapshot: dataSnapshot.getChildren()) {
System.out.println(userSnapshot.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
For more on this, see the Firebase documentation on ordering an filtering data.

Perform key Specific Query in Firebase

I have structure for database in this manner
-... location
-... messages
-... id1_id2
-... id3_id4
-... id5_id6
.
.
.
How can I access a object in messages where I just know id1 which is the key.
TIA.
Change your database to this:
Messages
userid1
userid2
message: hello
then to retrieve message, do this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("Messages").child(userid1);
ref.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String messages=ds.child("message").getValue().toString();
}
}
});
Try this one
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("location/messages");
ref.addListenerForSingleValueEvent(new ValueEventListener(){
#Override
public void onDataChange(DataSnapshot dataSnapshot){
for (DataSnapshot ds : dataSnapshot.getChildren()) {
if(ds.getKey().contains("bob")){
//Do something with the date
break;
}
}
}
});
Suppose your structure is like this:
You can do something like this, this will grab all nodes from messages that start with id1:
String id1 = "id1";
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("messages");
ref.orderByKey().startAt(id1).endAt(id1 + "\uf8ff").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snap : dataSnapshot.getChildren()) {
Log.d("SNAP", snap.getValue(String.class));
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I took the idea from the javascript implementation, but it also worked in Android, I've run a test on my device/database. Note that this method will work to grab data that starts with the given id.
EDIT:
The idea of querying firebase data that contains a certain string is discussed in this official post. Also, this question as well. The bottom line is that the api doesn't support these types of queries, the approach I mentioned above is the closest you can get of implementing a "SQL LIKE" in firebase. Currently, there's no way of searching for strings that END with another string. The endAt doesn't mean the string ends with id1, but rather that the range of values I want to retrieve finishes at (id1 + "\uf8ff"), that means any string starting with id1.
Your options are either change the schema or grab all messages and search locally (the suggestions of the other two answers).

How can I iterate through children of multiple push keys in Firebase Realtime Database?

I are trying to retrive lecture information. The information is structured like this:
I am trying to store details of each lecture in an array.
To iterate through the children try this:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Lectures").child("Saturday,March 03");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String batchname=datas.child("batch_name").getValue().toString();
//etc
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
the for(DataSnapshot datas: dataSnapshot.getChildren()) will let you iterate inside the push keys.
dataSnapshot.getChildren() will give you the direct children, which are the push keys in this case. Then using the for loop you will be able to access the data inside these keys

FirebaseDatabase Query : How to query some data basing on some values from other childs. For FirebaseRecyclerAdapter

I'm working on my app that has a fragment, this fragment displays new users with a follow button using this query :
query = mDatabaseref.child("users").orderByChild("date").limitToLast(10);
After a follow button is clicked, the current User Uid gets saved as a child in the other child that has a name "Follows" with 2 other child's "following" and "followers" as it showed in the below picture :
what I want to do is to make a Query for an other fragment with the name Following and show all the users that the Current user is following with the ability of getting their names, I was thinking of making a data dataSnapshot in the FirebaseRecyclerAdapter onBindViewHolder method basing on the Uid tooken from the childs, but I think it's gonna be complex, on the other hand, i tried to sort the follows in the user Info child direclty, but it leads to a strange behaviour on the RecyclerView.
I'm not going to write you all the code including your FirebaseRecyclerAdapter, I will show you just how to query to get the desired results. As i understand, here is the problem. So in order to achieve this, you need to query your database twice, once to get all those ids and second, based on those ids to get the names. So, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference followingRef = rootRef.child("follows").child(uid).child("following");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.getKey();
DatabaseReference userIdRef = rootRef.child("users").child(userId);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String name = dSnapshot.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userIdRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
followingRef.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be all the names of the followers that belong to a single user.

Categories