In my firebase database, I have list of users that have different information under them. I would like to retrieve information from a single userId, which I will define in the code and I want to only get information from that user.
My data looks like;
UserTable
{
"fmXWU324VHdDb8v6h7gvNjRojnu33" : {
"-KbJtw467nl6p253HZ537" : {
"Name" : "name1",
"Email" : "[email protected]",
"userid" : "fmXWU324VHdDb8v6h7gvNjRojnu33"
}
},
"pJtC45fW0MMi352UiPWnWdIS7h88" : {
"-Kb012ls9iMnzEL723o9I" : {
"Name" : "name2",
"Email" : "[email protected]",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
},
"-Kb0aq0q25FJq38256SrC" : {
"Name" : "name3",
"Email" : "[email protected]",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
},
"-Kb0atopfK64F6jy124Qi1u" : {
"Name" : "name3",
"Email" : "[email protected]",
"userid" : "pJtC45fW0MMi352UiPWnWdIS7h88"
}
}
and I want to, say for example read and display all data from this user "fmXWU324VHdDb8v6h7gvNjRojnu33"
. I am not sure how I can do that. I tried this, which seems logical but it doesn't seem to work:
df.child("UserTable").child(user.getUid())).addChildEventListener(new ChildEventListener()
it gives this error:
Can't convert object of type java.lang.String to type com.android.example.UserTable
In addition, I have tried:
df.child("UsersTable").child("userid").child(user.getUid()).addChildEventListener(new ChildEventListener()
I can seem to figure out what I am doing wrong, as what I have tried seems logical and should work. Please can someone help me out.
EDITED:
public ArrayList<data> get(String userID){
df.child("UsersTable").child(userID).addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
fetch(dataSnapshot);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
fetch(dataSnapshot);
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
return data;
Update
private void fetchData(DataSnapshot dataSnapshot)
{
for (DataSnapshot ds : dataSnapshot.getChildren())
{
Userdetail userdetail =ds.getValue(Userdetail.class);
userdetails.add(userdetail );
}
}
First initialize your database like this
mDatabase= FirebaseDatabase.getInstance().getReference().child("your_node_name");
then try setting a ValueEventListener
to your Database reference.
Inside the onDataChange
method you can retrieve your data like this
public void onDataChange(DataSnapshot dataSnapshot) {
User user= dataSnapshot.getValue(User.class);
}
EDIT:
ValueEventListener postListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
User user= dataSnapshot.getValue(User.class);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
};
mDatabase.addValueEventListener(postListener);