So I am trying to get immediate parent keys which are actually children under 'users' database.
Like so, the underlines ones -
My code for the same is as follows -
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
for( DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
String user = postSnapshot.getKey();
list.add(user);
}
}
But all it is doing is returning the below image -
First your database reference must be like this:
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference().child("users");
This is how you read the data:
ValueEventListener listener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds: dataSnapshot.getChildren()){
String user = ds.getKey();
list.add(user);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
//log error
Log.w(TAG, "loadPost:onCancelled", databaseError.toException());
}
};
databaseReference.addValueEventListener(listener);
Related
I want to read some specific child from the parent-child, by getchild() function but this will not work properly.
FirebaseUser FUser = mAuth.getCurrentUser();
String userid = FUser.getUid();
DatabaseReference DR;
DR = FirebaseDatabase.getInstance().getReference().child("HistoryTable").child(userid);
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Iterable<DataSnapshot> root = dataSnapshot.getChildren();
// Toast.makeText(getApplicationContext(), "ds "+dataSnapshot.getChildren(),Toast.LENGTH_LONG).show();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
// Toast.makeText(getApplicationContext(), "ds "+ds,Toast.LENGTH_LONG).show();
for (DataSnapshot d: ds.getChildren()) {
String Height = d.getKey() + d.getValue() + "\n".toString();
String ch = d.child("1Height:").getValue(String.class);
// tv.append(Height);
tv.append(ch);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
I want to get this four child from every key.
you have to add your push id in reference :-
DR = FirebaseDatabase.getInstance().getReference().child("HistoryTable").child(userid).child("push id");
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
// Iterable<DataSnapshot> root = dataSnapshot.getChildren();
// Toast.makeText(getApplicationContext(), "ds "+dataSnapshot.getChildren(),Toast.LENGTH_LONG).show();
for (DataSnapshot ds: dataSnapshot.getChildren()) {
// Toast.makeText(getApplicationContext(), "ds "+ds,Toast.LENGTH_LONG).show();
for (DataSnapshot d: ds.getChildren()) {
String Height = d.getKey() + d.getValue() + "\n".toString();
String ch = d.child("1Height:").getValue(String.class);
// tv.append(Height);
tv.append(ch);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
Try like this if you just want to read the value. if you want to read data only once use addListenerForSingleValueEvent()
*Try to read values by object stucture https://firebase.google.com/docs/database/android/read-and-write#basic_write
DR.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot d: ds.getChildren()) {
//below line may cause null pointer Exception
String Height = d.getKey() + d.getValue() + "\n".toString();
if(d.child("1Height:").getValue()!=null){
String ch = d.child("1Height:").getValue(String.class);
//tv.append(Height);
tv.append(ch);}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
To get the value of your 4UserId property, simply use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("HistoryTable").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String userId = ds.child("4UserId").getValue(String.class);
Log.d(TAG, userId);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be:
2Wwrjx...P2obFO83
I have the following Firebase Database :
I need to delete all the entries/database objects sharing the same "date_cours" type.
I tried the following method to delete all the entries sharing the same date_cours "10/09/2018", for example :
private void Delete_CR_Lessons(Date date) {
final String date_a_supprimer_string = DateFormat.getDateInstance(DateFormat.SHORT).format(date);
DatabaseReference drTest = FirebaseDatabase.getInstance().getReference("cours");
drTest.child("date_cours").orderByKey().equalTo("10/09/2018")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Tag", "test1");
for (DataSnapshot postsnapshot :dataSnapshot.getChildren()) {
Log.i("Tag", "test2");
String key = postsnapshot.getKey();
dataSnapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG: ", databaseError.getMessage());
}
});
}//fin de la methode Delete_CR_Lessons
I have no error during the execution of the method.
In the Logs, I can see my Log "test1" but not the log "test2".
Does anyone know what I am missing ?
You are providing wrong path and than you are trying to delete wrong datasnapshot value for example try to use: postsnapshot.getRef().removeValue(); instead of dataSnapshot.getRef().removeValue(); because dataSnapshot doesn't point to the value which you want to delete. That is why you used for loop to get all value nodes from your database. Check code below:
DatabaseReference drTest = FirebaseDatabase.getInstance().getReference("cours");
drTest.orderByChild("date_cours").equalTo("01/10/2018")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i("Tag", "test1");
for (DataSnapshot postsnapshot :dataSnapshot.getChildren()) {
Log.i("Tag", "test2");
String key = postsnapshot.getKey();
postsnapshot.getRef().removeValue();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("TAG: ", databaseError.getMessage());
}
});
I have this structure in my Firebase Real-time database :
How can I count the data and show it in my app, which listener shall I use to get all childrens?
There are a few ways in which you could achieve this.
I use the following way:
FirebaseDatabase.getInstance()
.getReference()
.child("demografi")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnap : dataSnapshot.getChildren()) {
YourObject object = dataSnap.getValue(YourObject.class);
// Use your object as needed
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
dataSnapshot returns the child referenced. Once you have it, all you have to do is iterate through them and you have access to "all children" as you wanted.
FirebaseDatabase.getInstance()
.getReference()
.child("demografi")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
/** Qty of data in demografi, this is what you want. */
long Count = dataSnapshot.getChildrenCount();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
if you want to monitor the count of data in realtime way,
you have to replace [addListenerForSingleValueEvent] with [addValueEventListener].
I will prefer this way -
String email, gender, nama;
DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("demografi");
databaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
// To get children count
dataSnapshot.getChildrenCount();
email = dataSnapshot.child("email").getValue().toString();
gender = dataSnapshot.child("gender").getValue().toString();
nama = dataSnapshot.child("nama").getValue().toString();
// and so on..
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s){
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
If you don't have a model class, you can simply use the String class. So to get all child's data, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference demografiRef = rootRef.child("demografi");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String nama = ds.child("nama").getValue(String.class);
Log.d("TAG", nama);
}
Log.d("TAG", String.valueOf(dataSnapshot.getChildrenCount()));
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
demografiRef.addListenerForSingleValueEvent(valueEventListener);
The output in your logcat will be all the names of all your users. As you can see, there is a second log statement which will print the total number of your children.
I have this code:
DatabaseReference mdatabase = FirebaseDatabase.getInstance().getReference("allmessages");
mdatabase.child(mAuth.getCurrentUser().getUid()).child(userID).child(uploadID).push().setValue("somevalue");
Then in another class I have this code:
DatabaseReference mdatabase = FirebaseDatabase.getInstance().getReference("allmessages");
mdatabase.child(mAuth.getCurrentUser().getUid()).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
//Loop through all files in Uploads DataBase
for(DataSnapshot postSnapshot : dataSnapshot.getChildren()){
AllChatMessagesGet allChatMessagesGet = postSnapshot.getValue(AllChatMessagesGet.class);
is it possible for me to get all value under mdatabase.child(mAuth.getCurrentUser().getUid()).child(userID).child(uploadID).push().setValue("somevalue"); by the code I used above.
Because it doesn't retrieve me anything back. I thought that the above code in addValueEventListener would go trough all child classes of mAuth.getCurrentUser().getUid() and retrive me the "somevalue".
But it doesn't. So how do I retrieve "somevalue". Is there any other way? because the codes are written in different classes and I dont know how to get .Child(userID) and .Child(uploadID) it would be problematic for me.
is there anyway for me to retrive all childrens of mdatabase.child(mAuth.getCurrentUser().getUid()) and their values that exist some child below it.
According to your comments, to get those ids that starts with -LD under -LCzWNw0nlC3GKsnPH8B node using only rootRef.child("AllChatMessages").child(uid), please use the followig code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("AllChatMessages").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
for(DataSnapshot dSnapshot : ds.getChildren()) {
for(DataSnapshot snap : dSnapshot.getChildren()) {
String key = snap.getKey();
Log.d("TAG", key);
}
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
The output will be all those ids that you are looking for.
Add and implement a ChildEventListener instead of a ValueEventListener.
Your "somevalue" should be in the DataSnapshot of the overriden onChildChanged method.
I have write up a code glimpse of it is in below code. What I was doing was getting value from the node of users. I have retracted all the children of it by the below code you may also try the same way maybe it would help you.
mFirebaseUserReference = FirebaseDatabase.getInstance().getReference();
userReference = mFirebaseUserReference.child("Users");
childEventListener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Log.d("Values",dataSnapshot+"");
HashMap temp = (HashMap) dataSnapshot.getValue();
if (temp!=null){
if (!temp.get("id").equals(FirebaseAuth.getInstance().getCurrentUser().getUid())){
SignInModel signInModel = new SignInModel();
signInModel.setPhotoUrl((String)temp.get("photoUrl"));
signInModel.setEmail((String)temp.get("email"));
signInModel.setName((String)temp.get("name"));
signInModel.setId((String)temp.get("id"));
arrayList.add(signInModel);
adapter.notifyDataSetChanged();
}
}
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
userReference.addChildEventListener(childEventListener);
Hope that helps.
The structure looks like this:
users
|----username1
|----uid:value
username2
|----uid:value
I'm trying to find the best way to get the username value based of the value of it's uid,
This need to be in Java code (Android), So far I found the following code:
Query uid = reference.child("users").orderByChild("uid").equalTo(uid);
uid.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot datas: dataSnapshot.getChildren()){
String keys=datas.getKey();
if (keys.equals(uid)) {
// uid found
} else {
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Try this code and create a model class to fetch value of Uid
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
users.orderByChild("uid").equalTo(uid).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot post:dataSnapshot.getChildren()){
//Use a model class to fetch user id like below
UIDDetails u=post.getValue(UIDDetails.class);
String user_id=u.getUid();
//Here all values will be equal to youy required uid if exists more than one
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Please add below code into your file:
DatabaseReference users= FirebaseDatabase.getInstance().getReference().child("users");
final Query userQuery = users.orderByChild("uid");
userQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
map.clear();
if(child.getkey().toString().equalsIgnoreCase(uid)){
//Get the node from the datasnapshot
String myParentNode = dataSnapshot.getKey();
for (DataSnapshot child: dataSnapshot.getChildren())
{
String key = child.getKey().toString();
String value = child.getValue().toString();
map.put(key,value);
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
databaseError.toException();
}
});