Firebase get all users in a parent node - java

I am trying to build a simple friend list, where the user can create some friend groups and each friend group can have a lot of friends, inside the friend group the user can add new friends by contact(inserting the phone number on a editText) the user is added in the list(I use recycleViews), each time I insert a new user in a friendList group in firebase it is added inside the group with the specific name(name can't be repeated for groups) with the userID and the value = true for that user, this is a representation of my firebase:
image the 't' refers to true
what I need, is to display all the users for a specific group, as long as I safe just the id inside my group, I need to get the entire user from that id, but not just 1 user I need to get them all.
So I did this:
private void prepareFriendList() {
myRef.child(id).child("FriendLists").child(group).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
currentFriends.add(snapshot.getKey());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
myRef.child(id).child("Users").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
User user = snapshot.getValue(User.class);
for(String item: currentFriends){
if (snapshot.getKey().equals(item)) {
usersList.add(user);
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mAdapter.notifyDataSetChanged();
}

Related

how update buttons (rooms) on specific date acording to database?

I create database using curentdate (1-25) as parent id and using room (08-00_11-00_karpet1-) as child id. inside this database are user information that order that room (child id) on that date (parent id).
Question 1
using this layout design, how do i disable button that have been ordered so that indicate that room no longer available.
(example. user order karpet 14-17 on 1-28, when user create order database will update database datajadwal based on date (parentid) >> room (childid) >> userinformation (email.name.phone.etc) )
Question 2
each date have 5 rooms. when specific date click, room button will disabled according to the data on datajadwal and on that date (parentid), if there are no room data (childid) that means that room are available.
my situation =
i don't know hot to get the childid
private void datajadwalupdate(){
databseJadwal = database.getReference("datajadwal").child(haritanggalOrder);
databseJadwal.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dateSnapshot: dataSnapshot.getChildren()) {
final String rooms = dataSnapshot.getKey();
databseJadwal.child(haritanggalOrder).child(rooms).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
this is where I'm, but got error on a null object reference
If I understand your question correctly, you will need all data under datajadwal to disable the correct buttons. In that case you can use a listener like this:
DatabaseReference ref = FirebaseDatabase.getInstance().getReference("datajadwal");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dateSnapshot: dataSnapshot.getChildren()) {
String date = dataSnapshot.getKey();
for (DataSnapshot bookingSnapshot: dateSnapshot.getChildren()) {
String booking = bookingSnapshot.getKey();
// TODO: parse the booking into the time slot and room name
String timeslot = ...
String room = ...
// TODO: find the button for the room name and time slot and disable it
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
throw databaseError.toException();
}
}
You need to iterate throught the childs of the snapshot and check the data, if there is user data then disable it.
DatabaseReference ref = rootRef.child(id).child(date);
ref.addValueEventListener(...
onDataChange...{
for (Snapshot child: dataSnapshot.getChildren()) {
//set the names as you are doing it
boolean occupied = child.hasChild("email)
button.setEnabled(!occupied)
}
}
You should create a POJO representing your entity and get the value from the snapshot child with getValue(YourPOJO.class)

How to get a node key from inner matching values

I need to get the key of each event that match the users ID's that I have looped before in another table, so, I have this table where the current userID that is logged in has a list of users that will assist to a certain event
Im logged in as the user MUTzo13NuJRlbbkZCDp2nCdHkIn1 , then I just get all the users below that id , so I know which one I invited
I have done that with this
mDatabase.child("userEvent").child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot snapshot1 : dataSnapshot.getChildren()){
final String users = snapshot1.getKey();
...
So , now my string of users has all the users from the current logged in one.
Now, since I have all those users that belongs to the logged in one , I want to loop another table, find the matching users and get the key (the event ID in which those users has not assisted)
Table events
I need to get for example the ID LT9d-sJCmMBUIW14AG8 if the users looped before are inside of it, so I just tried this
mDatabase.child("userEvent").child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot snapshot1 : dataSnapshot.getChildren()){
final String user = snapshot1.getKey();
//Now I go to the events table and try to get the event ID if those users are inside of them
mDatabase.child("events").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot snapshot2 : dataSnapshot.getChildren()){
if(snapshot2.equals(user))
Log.d(TAG, "onDataChange: "+snapshot2.getKey());
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
But it does not work, instead getKey returns the name node events, instead of the name of the node that the user belongs.
Any tip ?
EDIT:
Thanks Peter for the answer, I'm having a trouble that is the users are beign matched with events that they dont belong to
So , the problem is that its matching to events users that It does not belong to
Try the following:
mDatabase.child("events").orderByChild(user).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists()){
for(DataSnapshot snapshot2 : dataSnapshot.getChildren()){
String keys = snapshot2.getKey();
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
You need to add the user String that you retrieved in the first listener inside orderByChild() and then you will get a snapshot that contains that child. After looping you will be able to get the parent key of that child.

Firebase reading data from multiple references

I am trying to fetch data from Firebase database from multiple child in single function. I have two child nodes in Firebase Favorites and Users
I am using RecyclerView to show list of Favorites User but i want to fetch one value name "Online" from Users node.
I add addValueEventListener on Favorites and add addListenerForSingleValueEvent on Users within Favorites addValueEventListener, but my addListenerForSingleValueEvent give null value.
There is my code:
mFavouriteDBRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mList.clear();
if(dataSnapshot.getChildrenCount() > 0){
for(DataSnapshot snap: dataSnapshot.getChildren()){
final Favourites user = snap.getValue(Favourites.class);
final FavouritesList[] holdObj = null;
//if not current user, as we do not want to show ourselves then chat with ourselves lol
try {
if(mAuth.getCurrentUser().getUid().equals(user.getUserId())){
//Firebase Reading data
mUsersDBRef = FirebaseDatabase.getInstance().getReference().child("Users");
mUsersDBRef.child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mUsersDBRef.child(mAuth.getCurrentUser().getUid()).child("online").onDisconnect().setValue(false);
String local =dataSnapshot.child(mAuth.getCurrentUser().getUid()).child("online").getValue().toString();
if(local.equals("true")){
holdObj[0] = new FavouritesList(mAuth.getCurrentUser().getUid(),user.getFavouriteId(),user.getFavouriteName(),user.getFavouriteCity(),user.getFavouriteCountry(),user.getFavouriteAge(),user.getFavouriteGender(),user.getFavouriteKeyword(),user.getPushKey(), "true","Link");
}else{
holdObj[0] = new FavouritesList(mAuth.getCurrentUser().getUid(),user.getFavouriteId(),user.getFavouriteName(),user.getFavouriteCity(),user.getFavouriteCountry(),user.getFavouriteAge(),user.getFavouriteGender(),user.getFavouriteKeyword(),user.getPushKey(), "false","Link");
}
mList.add(holdObj[0]);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
populaterecyclerView();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Here my populaterecyclerView(); Class
private void populaterecyclerView(){
adapter = new UserFavouritesMeHomeListAdapter(context,mList);
adapter.setClickListener(UserFavouritesMeListHomeFragment.this);
recyclerView.setAdapter(adapter);
}
Thanks
Link of Image:
http://userdata.in/singls/images/profile/WobiUh7Zb2bjszmYN0LofK7Pm0z1_20180124042847_file_cover.jpg
Data want to fetch from while reading Favorite
http://userdata.in/singls/images/profile/WobiUh7Zb2bjszmYN0LofK7Pm0z1_20180124044659_file_cover.jpg

How to handle results from Firebase seeing that its aynchronous

How do I return combinedFoodItem from the code below. I have been using firebase for less than a week now and I still find this confusing. The summary is:
Food contains name and categoryId (which is from the FoodOption model)
public void getFoodItems() {
//get all the food options for the selected venue
final List<FoodItem> combinedFoodItem = new ArrayList<>();
filterRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
final FoodOption foodOption = dataSnapshot1.getValue(FoodOption.class);
final List<Food> foodList = new ArrayList<>();
meniItemFilter = menuItemReference.orderByChild("categoryId").equalTo(foodOption.getKey());
meniItemFilter.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot2 : dataSnapshot.getChildren()) {
Food food = dataSnapshot2.getValue(Food.class);
foodList.add(food);
}
FoodItem foodItem = new FoodItem(foodOption.getFoodCategory(), foodList, R.drawable.ic_banjo);
combinedFoodItem.add(foodItem);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
as firebase works in a reactive manner you can't return elements but listen for changes of them. You can define your combinedFoodItem outside the function (this is, for instance, as a class field) and then add the elements to the list (or clear the list every time the data changes if you want to reset the list this depends on the behavior of your list)

Storing firebase values into an array? Keep getting zero

I am trying to store userid's into uidMatches. When I do the first println I am getting the correct string array of matches, but when i do the second one it says my uidMatches array has nothing in it... "[ ]". I don't see how this is possible.
private void populateListView() {
final ArrayList<String> uidMatches = new ArrayList<String>();
final ArrayList<Profile> match_profiles = new ArrayList<Profile>();
users = database.getReference("Users");
user = FirebaseAuth.getInstance().getCurrentUser();
matches = database.getReference("Matches").child(user.getUid());
// Returns uid's for all profiles you matched with
matches.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()) {
String match = child.getValue().toString();
uidMatches.add(match.toString());
System.out.println("HERE ARE MATCHES 1: " + uidMatches);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
System.out.println("HERE ARE MATCHES 2: " + uidMatches);
// Loop to get all Profiles that match each "uidMatches" uid
for (int x=0; x<uidMatches.size(); x++)
{
users.child(uidMatches.get(x)).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren())
{
Profile profile = child.getValue(Profile.class);
match_profiles.add(profile);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
Picture of my firebase setup. I Blocked out the users unique ID's generated from FB login
This isn't a firebase issue it's simply a Java problem. The println at the end of your code gets run when the code first starts when the array is empty. The other println gets fired onDataChange so after the results are populated.

Categories