I have the following database. What I need is to get the total count of comments per post when posting UID equal to current_user_uid.
Any suggestion on how to do this?
To solve this, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Posts").orderByChild("uid").equalTo(current_user_uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
long count = ds.child("comments").getChildrenCount();
Log.d("TAG", "Count: " + count);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage());
}
};
query.addListenerForSingleValueEvent(valueEventListener);
Related
What I really need is to show every value in the "Income" field in TextView.
250
105
Is this possible? If it is possible please help me.
This is how I insert values to database
private void addReport() {
Float total_Income = Float.valueOf(tv_total_income.getText().toString());
String current_date = tv_current_date.getText().toString();
SimpleDateFormat sdf = new SimpleDateFormat("MMMM");
String currentDateandTime = sdf.format(new Date());
FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
DatabaseReference mDbRef = mDatabase.getReference("Reports"+"/"+currentDateandTime+"/"+current_date).child("Date");
mDbRef.setValue(current_date);
DatabaseReference mDbRef1 = mDatabase.getReference("Reports"+"/"+currentDateandTime+"/"+current_date).child("Income");
mDbRef1.setValue(total_Income);
}
While Sairaj Sawant's answer might work, keep in mind that there is no need to attach a listener at every iteration of the loop. A more convenient solution is to attach a listener only once, like in the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference juneRef = rootRef.child("Reports").child("June");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String totalIncome = "";
for(DataSnapshot ds : dataSnapshot.getChildren()) {
totalIncome = totalIncome + ds.child("Income").getValue(String.class) + " ";
}
Log.d("TAG", totalIncome);
textView.setText(totalIncome);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
juneRef.addListenerForSingleValueEvent(valueEventListener);
This code will work only if the Income property is of type String, as it is set in your 20-06-2020 child. However, the above code will not work if the value is set as an Integer as it set in your second 21-06-2020 child. Remember, both types of values must match. You either set both as String and the above code will work, or you set them as numbers, case in which you should use this line:
totalIncome = totalIncome + ds.child("Income").getValue(Long.class) + " ";
Try accessing the children of June under Reports and looping through to get income as below :
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference reportsRef = rootRef.child("Reports").child("June");
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
DatabaseReference keyRef = rootRef.child(key).child("income");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot ds1 : dataSnapshot.getChildren()) {
String income = ds1.getValue(String.class);
Log.d("TAG", income);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
keyRef.addListenerForSingleValueEvent(valueEventListener);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
reportsRef.addListenerForSingleValueEvent(eventListener);
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
My firebase database structure looks like this:
I'm using this code but it doesn't retrieving any data from database and sometime the getUid() produce NullPointerException. Can anyone help me to solve this problem?
mAuth = FirebaseAuth.getInstance();
mUser = mAuth.getCurrentUser();
userID = mUser.getUid();
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users");
mDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
showData(dataSnapshot);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
private void showData(DataSnapshot dataSnapshot) {
for (DataSnapshot ds: dataSnapshot.getChildren()) {
UserInformation uInfo = new UserInformation();
uInfo.setFullName(ds.child(userID).getValue(UserInformation.class).getFullName());
uInfo.setUsername(ds.child(userID).getValue(UserInformation.class).getUsername());
uInfo.setEmail(ds.child(userID).getValue(UserInformation.class).getEmail());
fullNameProfile.setText(uInfo.getFullName());
usernameProfile.setText(uInfo.getUsername());
emailProfile.setText(uInfo.getEmail());
}
}
To simply get user data from the database please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.child("Email").getValue(String.class);
String fullName = dataSnapshot.child("FullName").getValue(String.class);
String password = dataSnapshot.child("Password").getValue(String.class);
String userName = dataSnapshot.child("Username").getValue(String.class);
Log.d(TAG, userName);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
Or even simpler using a UserInformation class:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("Users").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
UserInformation uInfo = dataSnapshot.getValue(UserInformation.class);
Log.d(TAG, uInfo.getUsername());
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
I am trying to retrieve an url from Firebase in Android. However, my problem is that I can't retrieve the url without also getting the unique key of the child.
The value I am trying to retrieve is the following:
Down below is the code I use to retrieve the data from firebase.
final FirebaseDatabase database = FirebaseDatabase.getInstance();
myRef = database.getReference().child("LoadItems");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot child : dataSnapshot.getChildren() ){
String key;
key = child.getKey();
Log.d(TAG, "onDataChange: " + key);
Log.d(TAG, "onDataChange: " + child.getValue());
}
}
#Override
public void onCancelled(DatabaseError databaseError) { }
});
So what I am trying to get is what the url alone.
There is no need to know any key in order to get that URL. So please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference shoesRef = rootRef.child("LoadItems").child("Shoes");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String url = ds.getValue(String.class);
Log.d(TAG, url);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
shoesRef.addListenerForSingleValueEvent(valueEventListener);
I did't want to make it key and value , I have tried a lot to find a solution, but I can't
And this my code when I tried to get it by key and value
mFriendID = (DatabaseReference) FirebaseDatabase.getInstance().getReference().child("friends").child(current_user).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
fri_id = dataSnapshot.child("fri_id").getValue().toString();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
To get the highlighted key, please use the following code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference uidRef = rootRef.child("friends").child(uid);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String key = ds.getKey();
Log.d("TAG", key);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {}
};
uidRef.addListenerForSingleValueEvent(valueEventListener);
So I have some data in my Firebase. It's structure is
(assume that there is more data)
I want to get the records where banknoteType ="100_dollar" and userId="1057..."
DatabaseReference database = FirebaseDatabase.getInstance().getReference("userBanknoteAmount");
Query firebaseQuery = database.orderByChild(1057...).equalTo(1057...);
firebaseQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
//todo
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.w("onCancelledError", "loadPost:onCancelled", databaseError.toException());
}
});
But the onDataChangeevent doesn't fire... What am I mistaking?
EDIT: I am trying to debug it and neither onDataChange nor onCancelled breakpoints stop there
EDIT 2 : The current code I am using is
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userBanknoteAmountRef = rootRef.child("userBanknoteAmount");
Query firebaseQuery = userBanknoteAmountRef.orderByChild("userId");//.equalTo(userId);
firebaseQuery.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot postSnapshot : dataSnapshot.getChildren()) {
Log.d("test", "onDataChange: "+postSnapshot);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.wtf("onCancelledError", "loadPost:onCancelled", databaseError.toException());
}
});
EDIT 3: https://i.stack.imgur.com/iBkcx.png
Firebase Realtime database does not allow you to chain multiple filter methods. If you want to get the records where : userId="1057...", please change the following line of code:
Query firebaseQuery = database.orderByChild(1057...).equalTo(1057...);
with
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference userBanknoteAmountRef = rootRef.child("userBanknoteAmount");
Query firebaseQuery = userBanknoteAmountRef.orderByChild("userId").equalTo(1057...);
If you want to get all the records where banknoteType ="100_dollar" and userId="1057...", please see my answer from this post.
According to your edited post, please also change this line of code:
Log.d("test", "onDataChange: "+postSnapshot);
to
Log.d("test", "onDataChange: "+postSnapshot.child("userId").getValue(String.class));