Firebase - getValue in third child return null - java

I have a problem, when I want get value from firebase, getValue() return null
DataSnapshot appleSnapshot and DataSnapshot dataSnapshot - in console I see Key and Value correctly in Firebase too
Database Structure
Debugging
DataSnapshot setting - return Key but don't return Value (null)
String settingKey - return correctly String Key
String settingValue - return null
Why i cant get Value from my deeper childs?
private void readData(final ValidateJoinInterface validateJoinInterface, final String name, final String password, final String user) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot appleSnapshot : dataSnapshot.getChildren()) {
DataSnapshot setting = appleSnapshot.child(name).child("Settings").child("Password");
String settingKey = (String) appleSnapshot.child(name).child("Settings").child("Password").getKey();
String settingValue = (String) appleSnapshot.child(name).child("Settings").child("Password").getValue();
}
validateJoinInterface.validateJoin(correctName, correctPassword, correctUserId);
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.e("DTAG", "onCancelled", databaseError.toException());
}
});
}

Assuming that the name varaible holds a String value like in your example Aa and also assuming that Aa is a direct child of your Firebase root, to solve this, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference settingsRef = rootRef.child(name).child("Settings");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.child("Name").getValue(String.class);
String password = dataSnapshot.child("Password").getValue(String.class);
Log.d("TAG", name + " / " + password);
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
settingsRef.addListenerForSingleValueEvent(valueEventListener);
The output will be: Aa / Aaa.

You can getting any value like :
FirebaseDatabase.getInstance().getReference().child(name).child("Settings").child("Password")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot messageSnapshot : dataSnapshot.getChildren()) {
Log.d(TAG,"KEY - "+messageSnapshot.getKey() + "VALUE - "+messageSnapshot.getValue());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Crashlytics.logException(databaseError.toException());
sendMessageListener.onSendMessageFailure(databaseError.getMessage());
}
});

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

Firebase value not updating

Everything is working fine, I think just userDataModel.setUserRating(aFloat / (int) dataSnapshot.getChildrenCount()); is not giving value.
And String.valueof(aFloat / (int) dataSnapshot.getChildrenCount()));
Is also giving the correct value.
FirebaseDatabase.getInstance().getReference().child("Users").child(userDataModel.getUserID()).child("Ratings")
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
userDataModel1 = dataSnapshot.getValue(UserDataModel.class);
aFloat = aFloat + Float.parseFloat(Objects.requireNonNull(dataSnapshot1.getValue()).toString());
}
userDataModel.setUserRating(aFloat / (int) dataSnapshot.getChildrenCount());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
UserDataModel
public class UserDataModel {
float userRating;
public float getUserRating() {
return userRating;
}
public void setUserRating(float userRating) {
this.userRating = userRating;
}
}
Image URL: https://i.stack.imgur.com/t14Cc.png
This is happening maybe because userDataModel.setUserRating(aFloat / (int) dataSnapshot.getChildrenCount()); is returning null so you don't get a value
The problem in your code us the fact that your UserDataModel has a field named userRating, while in your database the property is actually a uid. This property is dynamic, so you cannot use a POJO class for that. If you want to get the values of those ratings, please try this:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ratingsRef = rootRef.child("Users").child(uid).child("Ratings");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
double rating = ds.getValue(Double.class);
Log.d("TAG", "rating: " + rating);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
ratingsRef.addListenerForSingleValueEvent(valueEventListener);
The output in the logcat will be values of all ratings that exist within the Ratings node.
3.5
2
Now, you can simply make the average or whatever you need with those values.

How to retrieve all data from Android Firebase database databaseRef->userID->uniqueKey

This is the Firebase database:
ExchangeItemsData: -> reference
lhmuj6n3g6Su1rv7XJLq5tV62yr2 -> userId
-LQQ7scByWcswW2VIPM5 -> UniqueKey inserted by .push().getKey();
// below is the data under the uniquekey
exchangeProductName:
"Pen"
imageUrl:
"https://firebasestoragse.googleapdfis.codfm/v04df/b/dbin..."
phoneNo:
5465464
productDesc:
"Used"
productName:
"GelPen"
userID:
"lhmuj6n3g6Su1rv7XJLq5tV62yr2"
I need to show all data of every user in this ExchangeItemsData reference. I've tried many ways but i failed. If anyone can help me out here it would be so nice of you.
Thanks in advance.
To get all those values that belong to all users, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference ref = rootRef.child("ExchangeItemsData");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot dSnapshot : dataSnapshot.getChildren()) {
for(DataSnapshot ds : dSnapshot.getChildren()) {
String imageUrl = ds.child("imageUrl").getValue(String.class);
String phoneNo = ds.child("phoneNo").getValue(String.class);
String productDesc = ds.child("productDesc").getValue(String.class);
String productName = ds.child("productName").getValue(String.class);
String userID = ds.child("userID").getValue(String.class);
Log.d(TAG, productName);
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
ref.addListenerForSingleValueEvent(valueEventListener);
The output in the logcat will be all the product names of all products of all users.
Try this code to retrieve values from your database
public class Demo extends Activity{
FirebaseAuth mAuth;
String currentUId;
DatabaseReference usersDb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
mAuth=FirebaseAuth.getInstance();
currentUId=mAuth.getUid();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("ExchangeItemsData");
ref.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
if(dataSnapshot.exists() && dataSnapshot.hasChildren()){
for (DataSnapshot userId : dataSnapshot.getChildren()) {
if(!userId.getKey().equals(currentUId)) {
usersDb.child(userId).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot1) {
if(dataSnapshot1.hasChildren()){
for (DataSnapshot userKey : dataSnapshot1.getChildren()) {
String exchangeProductName = dataSnapshot1.child(userKey).child("exchangeProductName").getValue().toString();
String imageUrl = dataSnapshot1.child(userKey).child("imageUrl").getValue().toString();
String phoneNo = dataSnapshot1.child(userKey).child("phoneNo").getValue().toString();
String productDesc = dataSnapshot1.child(userKey).child("productDesc").getValue().toString();
String productName = dataSnapshot1.child(userKey).child("productName").getValue().toString();
String userID = dataSnapshot1.child(userKey).child("userID").getValue().toString();
//From here do whatever you want to do with those values
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
}
}
}
}
}

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

Categories