Firebase database retreiving value, is this possible - java

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.

Related

How do I get immediate parent keys in firebase

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);

Getting Data from Firebase realtime database, Android Studio, Java

I am looking for a way to get data from the firebase real-time database in a format like an array[] or a String.
My database looks like this:
Link to image of database
Or:
Database
|
-->Users
|
-->UID1
-->UID2
This is at the root of the database
I want to get a list of all of the UIDs in the "Users" child.
This is the code I have so far and am a bit stuck on:
DatabaseReference databaseReference = firebaseDatabase.getReference("Users");
databaseReference.addValueEventListener(
new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String UIDs = dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I am a bit of a rookie as it comes to java, android studio, and firebase. I am trying to get the data in a format I know how to use like a String or an Array[] of Strings. I looked around if other people had maybe asked the same question, but I could get the answers to those questions to work/didn't understand them.
Thanks in advance for your time!
To get the a list of uids, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String uid = ds.getKey();
list.add(uid);
}
//Do what you need to do with your list
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
usersRef.addListenerForSingleValueEvent(valueEventListener);
I recommend you to use the list only inside the callback otherwise it will be empty. If you want to use it outside the onDataChange() method, I recommend you see the last part of my anwser from this post in which I have explained how it can be done using a custom callback. You can also take a look at this video for a better understanding.
For your above question I will give both ways: ArrayList or String with delimiters
ArrayList<String> uids = new ArrayList<String>();
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids.add(snapshot.getKey());
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
For String
String uids = "";
FirebaseDatabase.getInstance().getReference("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
for(DataSnapshot snapshot : dataSnapshot.getChildren()) {
uids += snapshot.getKey() + ",";
}
}
}
#Override
public void onCancelled(DatabaseError error) {
}
});
This gives an output such as: uid1,uid2,uid3,.....uidn,
You can try this:
DatabaseReference ref=
FirebaseDatabase.getInstance().getReference("Users");
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (dataSnapshot.exists()) {
int i = 0;
for(DataSnapshot d : dataSnapshot.getChildren()) {
name[i] = d.getKey();
i++;
}
}
}//onDataChange
#Override
public void onCancelled(DatabaseError error) {
}//onCancelled
});
name[] is an array of strings!

How to get all child's data in firebase and show it into my android app?

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.

Firebase realtime database - how to get parent name based on a value of one of its keys

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();
}
});

Firebase Data retrieval in array

This is my Firebase realtime database structure:
How to get these data in a List to pass the data to the Model Class.
When I tried by generation data like below and it works.
listCourse = new ArrayList<>();
listCourse.add(new CourseModel("UserID", "CourseCode", "CourseName"));
listCourse.add(new CourseModel("122345", "TMN1234","System Programming"));
I just want get the data from firebase in this format..
You can retrieve list by this method.
Firebase ref = new Firebase(FIREBASE_URL);
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
Log.i("Count " ,""+snapshot.getChildrenCount());
for (DataSnapshot postSnapshot: snapshot.getChildren()) {
CourseModel course = postSnapshot.getValue(CourseModel.class);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Log.e("The read failed: " ,firebaseError.getMessage());
}
});
Please refer this documentation: https://firebase.google.com/docs/database/android/lists-of-data
if (dataSnapshot.exists()) {
int i = 1;
for (DataSnapshot dataSnapshot1 : dataSnapshot.child(userID).child("Course").getChildren()) {
coursecode[i]= dataSnapshot1.getKey();
coursename[i]=dataSnapshot.child(userID).child("Course").child(coursecode[i]).child("CourseName").getValue(String.class);
listCourse.add(new CourseModel(userID,coursecode[i],coursename[i]));
i++;
}
}
I figured it out.. this is working for me..
To Access Child you can to create reference.!
DatabaseReference userRef= FirebaseDatabase.getInstance().getReference("users");
DatabaseReference userChildRef= userRef.child(childId);
DatabaseReference userCourseRef= userChildRef.child("courses");
DatabaseReference userCourseIdRef= userCourseRef.child(courseId);
userCourseIdRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.i(TAG, dataSnapshot.getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w(TAG, "onCancelled", databaseError.toException());
}
});
Tol solve this, there are to ways. First would be to get the data as objects of CourseModel class like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference coursesRef = rootRef.child("Users").child(uid).child("Courses");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<CourseModel> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
CourseModel courseModel = ds.getValue(CourseModel.class);
list.add(courseModel);
}
//Do what you need to do with the list of CourseModel objects
Log.d("TAG", list.ToString);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
coursesRef.addListenerForSingleValueEvent(valueEventListener);
The second one, would be to get the courseName as a String like this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference coursesRef = rootRef.child("Users").child(uid).child("Courses");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
List<String> list = new ArrayList<>();
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String courseName = ds.child("CourseName").getValue(String.class);
list.add(courseName);
}
//Do what you need to do with the list of strings
Log.d("TAG", list.ToString);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
coursesRef.addListenerForSingleValueEvent(valueEventListener);

Categories