whats wrong with this code in firebase and android - android

usersRef= myRef.child("users");
usersRef.orderByChild("name").equalTo("yair").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user=new User();
user.setName(dataSnapshot.getValue(User.class).getName());
user.setEmail(dataSnapshot.getValue(User.class).getEmail());
user.setId(dataSnapshot.getValue(User.class).getId());
user.setPhone_num(dataSnapshot.getValue(User.class).getPhone_num());
my firebase looks like that:
users
Y6NKciGllTgkLXlMj9YLlAFuw522
email:
"yk.yair#gmail.com"
id:
"Y6NKciGllTgkLXlMj9YLlAFuw522"
name:
"yair"
phone_num:
"050-7777151"
kfby10Wy16Rx12v7Mx0sksqUTE72
email:
"aaa"
id:
"kfby10Wy16Rx12v7Mx0sksqUTE72"
name:
"aaa"
phone_num:
"(050)7777151"
it seems that the user always stays null;
can anyone help?

To solve this, please use this code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("users");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String email = ds.child("email").getValue(String.class);
User user = new User();
user.setEmail(email);
//and so on
Log.d("TAG", email);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
usersRef.addListenerForSingleValueEvent(eventListener);
You output will be:
yk.yair#gmail.com
Another approach will be just to change the DatabaseReference and use the same code like this:
DatabaseReference usersRef = rootRef.child("users").child(userId);
In which userId is the unique id generated by the push() method.
Hope it helps.

try this:
mFirebaseDatabase = FirebaseDatabase.getInstance();
mFirebaseDatabase.getReference().child("users").orderByChild("name").equalTo("yair").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.getValue() == null){
Log.i("IS NULL", "IS NULL");
} else{
User user = dataSnapshot.getValue(User.class);
Log.i("user name", user.getName());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
and make sure that your database is structured like this:
enter image description here

Related

Android - Firebase getting all the data that is on another table

In practice, people can send requests to each other. What I want to do is to show all the requests sent to one person in that person's profile. I can show all users information with firebase adapter in recyclerview but I could not show only request senders. How can I do? I'd be very happy if you could give an idea to us.
As I understand you want to show the children names of the parent you can use this code.
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Friend_req").child("recieved").child("id_of_reciepent");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String request_sender_id = (String) ds.getKey();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
ref.addListenerForSingleValueEvent(eventListener);
To display the names only of the friends who sent a friend request, you need to query your database twice. Please use the following code in order to achieve this.
String uid = firebaseAuth.getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Friend_req").child("recieved").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
DatabaseReference userRef = rootRef.child("Users").child();
ValueEventListener eventListener = new ValueEventListener(key) {
#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) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
Your output will be:
Bob
Second Friend

Followers structure firebase android

I want to implement followers functionality in my android application. 'First' image refers to the list of user i followed. 'second' image have all ids of all the posts that users post and 'third' image havin post details. all i want to do is to load only the post of those users that i've followed.
What i am doing is, i get emails from followers node and by using indexed recyclerview i load the data but its not working because recyclerview is not getting dynamic reference. Any sugested solution ?
first
second
third
In order to achieve this, you need to query your database for three times like this:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String userEmail = firebaseUser.getEmail();
String encodedUserEmail = userEmail.replace(".", ",");
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userEmailFromFollowersRef = rootRef.child("followers").child(encodedUserEmail);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String followerEmail = ds.getKey();
DatabaseReference my_postsRef = rootRef.child("my_posts").child(followerEmail);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
String postId = dSnapshot.getKey();
DatabaseReference postsRef = rootRef.child("posts").child(postId);
ValueEventListener vel = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child : dataSnapshot.getChildren()) {
String postText = child.child("postText").getValue(String.class);
Log.d("TAG", postText);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
postsRef.addListenerForSingleValueEvent(vel);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
my_postsRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userEmailFromFollowersRef.addListenerForSingleValueEvent(eventListener);

How can I give access to certain objects in Firebase database based on id

I have this data structure:
The red arrows points at animal IDs, and the blue arrow points at user IDs. Every user have one or many animals.
I have tried different methods for showing only the animals that have id that is stored in the current user node.
Example: If I have UID = 48onHXIxgDP465j5WW16oo7psNm2 (the first one in "users") I want to show the data from: "dog2" and "dog3".
Now iIhave the following code that gets snapshot from the "animals" node in the database, and then gets data from every child.
myAnimalRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<AnimalCard>();
for(DataSnapshot dataSnapshot1 :dataSnapshot.getChildren()){
AnimalCard value = dataSnapshot1.getValue(AnimalCard.class);
AnimalCard animal = new AnimalCard();
String name = value.getName();
int age = value.getAge();
String url = value.getUrl();
animal.setName(name);
animal.setAge(age);
animal.setUrl(url);
list.add(animal);
}
recyclerViewSetAdapter();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG1, "failed to read value: " + databaseError.toException());
}
});
How can get my code to filter out every animal that does not have their ID in the user node?
The reason I want to make the user get access with an UID stored in the database is because later on I want to make it so that multiple users can get access to the same animal.
To achieve this, you need to query your database twice. Please use the following code:
FirebaseUser firebaseUser = firebaseAuth.getCurrentUser();
String uid = firebaseUser.getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = usersRef.child("users").child(uid);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String aid = ds.getKey();
DatabaseReference animalRef = rootRef.child("animals").child(aid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dSnapshot) {
int age = dSnapshot.child("age").getValue(Integer.class);
String name = dSnapshot.child("name").getValue(String.class);
String url = dSnapshot.child("url").getValue(String.class);
Log.d("TAG", age + " / " + name + " / " + url);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
animalRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(eventListener);
In which uid is the id of the logged-in user and aid is the id of the animal. Your output will be:
11 / dog1 / http...
12 / dog2 / http...
Hope you find this helpfull.!
Get Object in Your Model Class and Store that Object in List for Further user.!
You can get specific object as well simple using
mdatabaseRef.child("animals").orderByChild().equalTo("value")
and also you can add check on key by orderByKey()
private FirebaseAuth mAuth;
private FirebaseDatabase mdatabase;
private DatabaseReference mdatabaseRef;
mAuth = FirebaseAuth.getInstance();
mdatabase = FirebaseDatabase.getInstance();
mdatabaseRef = mdatabase.getReference();
ArrayList<User> allUserList = new ArrayList<>();
Array<Animal> allAnimalList=new ArrayList<>();
mdatabaseRef.child("animals").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
Animal animal = childSnapshot.getValue(Animal.class);
allAnimalList.add(animal );
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
mdatabaseRef.child("users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot childSnapshot : dataSnapshot.getChildren()) {
String key = childSnapshot.getKey();
User user = childSnapshot.getValue(User .class);
allUserList.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I ended up taking Alex Mamo's answer and tweak with a litte bit.
This is the code i'am using:
uid = currentUser.getUid();
mRootRef = FirebaseDatabase.getInstance().getReference();
final DatabaseReference myUserRef = mRootRef.child("users").child(uid);
Log.d(TAG1, uid);
myUserRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
list = new ArrayList<AnimalCard>();
for(DataSnapshot ds : dataSnapshot.getChildren()){
String aid = ds.getKey();
DatabaseReference myAnimalRef = mRootRef.child("animals");
Query query = myAnimalRef.orderByKey().equalTo(aid);
query.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds2 : dataSnapshot.getChildren()){
AnimalCard value = ds2.getValue(AnimalCard.class);
AnimalCard animal = new AnimalCard();
String name = value.getName();
int age = value.getAge();
String url = value.getUrl();
animal.setName(name);
animal.setAge(age);
animal.setUrl(url);
list.add(animal);
}
recyclerViewSetAdapter();
progressDialog.dismiss();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
The main difference is that i'am using a query to filter out every Animal that does not have the aID that the currentUser have.

How to check orderbychild value exist?

I successfully get the username by searching the subject which is saved under username in the tlocation. But what if the subject totally not exist under all username so how I am gonna detect whether the subject exist in the tlocation? If you got any idea please share it to me thank you.
here's my code
tref.orderByChild("subject").equalTo(ssubject).
addValueEventListener(new ValueEventListener() {
//ssubject is user selected subject
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (final DataSnapshot u: dataSnapshot.getChildren()) {
if(u.child("subject").getValue().equals(ssubject)){
// do some code here
}else{
searchuserlist.setEmptyView(findViewById(R.id.stv));
}
here's my database structure
This is how you can verify if the subject exists:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userRef = rootRef.child("tlocation").child("rexyou0831");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.child("subject").exists()) {
//do something
} else {
//do something else
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
userRef.addListenerForSingleValueEvent(eventListener);
I have used rexyou0831 as an example. Instead of rexyou0831 you can use the userName variable.

Get linked data from Firebase

My firebase structure looks like this:
The groups use keys generated by firebase, 0 and 1 are just examples.
In those groups there is more data like "groupname".
How should I retrieve the groupnames of all groups linked to a user?
I'm on Android.
Solved by Alex.
Assuming that the groups node is a direct child of your Firebase root and inside a single group, there is a key named groupName, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference groupsRef = rootRef.child("groups");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.child("name").getValue(String.class);
Log.d("TAG", name);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
};
groupsRef.addListenerForSingleValueEvent(eventListener);
If you need to be able to get only the group names of the groups that your users are linking to, you need to query twice like this:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userGroupsRef = rootRef.child("users").child(userKey).child("groups");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String groupKey = ds.getKey();
DatabaseReference groupKeyRef = rootRef.child("groups").child(groupKey);
ValueEventListener valueEventListener = 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) {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
};
groupKeyRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
};
userGroupsRef.addListenerForSingleValueEvent(eventListener);
In which userKey is the key of the user from which you want the get the group ids.

Categories

Resources