I have to fetch all children data from firebase real time database? I want to fetch received messages of User2. How to do that? Database example is as given below -
To be able to fetch the children data, try the following:
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("users").child("User1").child("MSG_TYPE_SENT");
reference.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String msgContent=datas.child("msgContent").getValue().toString();
String msgType=datas.child("msgType").getValue().toString();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
This will give you the msgContent and the msgType, to retrieve any data from the database, you need to pass through every node example:-
getReference("users").child("User1").child("MSG_TYPE_SENT");
Then you can loop inside the ids and retrieve the data.
Here you can fetch the User2 Messages Received
DatabaseReference mDatabase = FirebaseDatabase.getInstance().getReference("users");
mDatabase.child("User2").child("MSG_TYPE_RECEIVED").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot spanshot : dataSnapshot.getChildren()){
String content=snapshot.child("msgContent").getValue(String.class);
String type=snapshot.child("msgType").getValue(String.class);
//then you can log those values
Log.d("Values:",""+content+""+type);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
If the message received change at any time (lets say you want to implement the delete option in realtime of the message like whatsapp) .addValueEventListener will update your UI in realtime if you have coded to show that the message has been deleted
Related
I need to get the specific user data using the user email on the real time database. This is my code, This code running without errors but the data is not display in the interface.I think datasnapshot retrieving part is not correct. please help me to solve this.
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String userEmail = user.getEmail();
DatabaseReference rootReference = FirebaseDatabase.getInstance().getReference();
Query myUsersQuery = rootReference.child("Children").orderByChild("childrenParentEmail").equalTo(userEmail);
myUsersQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("Children").getValue(String.class);
childrenNameEdt.setText(name);
childrenBirthdayEdt.setText(dataSnapshot.child("childrenBirthday").getValue(String.class));
childrenParentNameEdt.setText(dataSnapshot.child("childrenParentName").getValue(String.class));
childrenParentAddressEdt.setText(dataSnapshot.child("childrenParentAddress").getValue(String.class));
childrenParentContactNumberEdt.setText(dataSnapshot.child("childrenParentContactNumber").getValue(String.class));
childrenParentEmailEdt.setText(dataSnapshot.child("childrenParentEmail").getValue(String.class));
childrenTransportTypeEdt.setText(dataSnapshot.child("childrenTransportType").getValue(String.class));
childrenTransportContactNumberEdt.setText(dataSnapshot.child("childrenTransportContactNumber").getValue(String.class));
//childrenID.setText(dataSnapshot.child("password").getValue(String.class));
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
throw error.toException();
}
});
When you execute a query against the Firebase Realtime Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your code will need to handle that list, by looping over dataSnapshot.getChildren(). So something like:
myUsersQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot: dataSnapshot.getChildren();
String name = snapshot.child("Children").getValue(String.class);
childrenNameEdt.setText(name);
...
I need to display list of all users (Name, date and status) in a single list where status="Leave Pending" as pointed by red arrow. I wrote the following code to do this but it is not giving me username in the list.
As I used nested for each loop for this but not getting username. Kindly suggest me some solution to display the username too.
In my code:
LeaveRequestsInfo is the model class for mapping data.
requestsInfo is the object of modal class in which i am mapping my data.
listViewRequests is the ListView
requestsList is the object of List
To solve this, you need to query the database twice, once to get the user id and second, based on that id to get the name of the user. This can be done in a very simple way, using the String class, so please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference attendanceRef = rootRef.child("Attendance");
Query query = attendanceRef.orderByChild("status").equalsTo("Leave Pending");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String id = ds.child("id").getValue(String.class);
DatabaseReference idRef = rootRef.child("Users").child(id);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("name").getValue(String.class);
Log.d("TAG", name);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
idRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be all the names of all attendances where the status is Leave Pending.
I am working on app where I want to show the data only of the users whose contact numbers are saved in the phone. So, I retrieved a list of contact numbers contactList. Now, I want to get all the contactList user's post from Firebase. Is there any way I can ask the Firebase for only those nodes in my contactList. One Way is to retrieve all users and then get relevant users from that (like I did below). Is there any better way to do so ?
Users: {
7828272892 : {
name: xyz,
gender: male,
phoneNo: 7828272892
Posts: {
SomeKey1: {
content: "This is post 1", Var2: "kkk"} }},
7924272894 : {name: abc, gender: male, phoneNo: 7924272894}
}
Code:
databaseReference.child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
List<Post> allItems = new ArrayList<Post>();
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
if (contactList.contains(postSnapshot.child("phoneNo").getValue())) {
// retrieve posts
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Is there any way I can ask the firebase for only those nodes in my contactList?
Yes, the way in which you already do this.
Is there any better way to do so?
The way in which you do this is a common practice used in Firebase. You query the database and check is the data already exists in the list, in your case in the contactList. If the list contains that phoneNo then you can retrieve the posts.
Try this code to read multiple nodes data..
mFirebaseInstance = FirebaseDatabase.getInstance();
mDatabase = mFirebaseInstance.getReference("usersDb/UserTable");
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUserList.clear();
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
User user = dataSnapshot1.getValue(User.class);
mUserList.add(user); // add all data into list.
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
In my application I want to retrieve a single value from a particular id. The below screenshot is my database structure:
I want to retrieve the count of likes from database.
This is what I have tried:
public String getLikesCount(String USER_ID){
mref = FirebaseDatabase.getInstance().getReference("user").child(USER_ID);
return currentLike;
}
I don't know what to do after this to get likes count. Can anyone help me please?
do the following:
mref = FirebaseDatabase.getInstance().getReference("user").child(USER_ID).child("likes");
mref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String likes = dataSnapshot.getValue(String.class);
//do what you want with the likes
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am trying to make an event sorter app. I'm trying to grab the friends arraylist from the database, and add the event_key under each friend value in the database.
final ArrayList<String> friends= new ArrayList<String>();
hello.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dsp : dataSnapshot.getChildren()) {
friends.add(String.valueOf(dsp.getKey()));
}
mDatabaseUserEvents.child(invited_list).child(event_key).setValue(true);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
However, I get an error saying that ArrayList is not compatible.
The database structure I am trying to aim for is this:
Events:
-User1:
-event_key:true
-User2:
-event_key:true
I am pretty sure I need to use a for loop, but confused on how to achieve it. Thanks!
Because Firebase is a NoSQL database, it is structured as pairs of key and values. So every child is a Map and not an ArrayList. It's true that you can get a value from the database and store into an ArrayList but not in the way you do, because of the asynchronous behaviour of onDataChange() method, your friends ArrayList will always be empty. This is happening because onDataChange() method is called even before you are trying to add those values to that ArrayList.
If you want to set true for all the event_key coresponding to each user and assuming that Events node is a direct child of Firebase-database, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference eventsRef = rootRef.child("Events");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userKey = ds.getKey();
Log.d("TAG", userKey);
eventsRef.child(userKey).child("event_key").setValue(true);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
eventsRef.addListenerForSingleValueEvent(eventListener);