How to get total number of child from firebase database - android

I have created an android app which stores the value of User class in the following manner.
{
"users" : {
"Om8VuPSCcvg7d5jsYtZvPTWpm5o1" : {
"email" : "tavinder12singh#gmail.com",
"name" : "Ajay",
"uId" : "Om8VuPSCcvg7d5jsYtZvPTWpm5o1"
},
"v1dHuFXkfJYt6fYppICQS6rjxiw2" : {
"email" : "tavinder123singh#gmail.com",
"name" : "Tavinder Singh",
"uId" : "v1dHuFXkfJYt6fYppICQS6rjxiw2"
}
}
}
My User class:
#IgnoreExtraProperties
public class User implements Parcelable {
public String uId;
public String email;
public String name;
public User() {
}
public User(String uId, String email, String name) {
this.uId = uId;
this.email = email;
this.name = name;
}
protected User(Parcel in) {
uId = in.readString();
email = in.readString();
name = in.readString();
}
public static final Creator<User> CREATOR = new Creator<User>() {
#Override
public User createFromParcel(Parcel in) {
return new User(in);
}
#Override
public User[] newArray(int size) {
return new User[size];
}
};
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel parcel, int i) {
parcel.writeString(uId);
parcel.writeString(email);
parcel.writeString(name);
}
}
I am using the following code to save the data
FirebaseUser user = mAuth.getCurrentUser();
DatabaseReference database = FirebaseDatabase.getInstance().getReference();
database.child("users").child(user.uId).setValue(user);
But when I am trying to count the total number of child the "users" have, all I am getting is 0.
I am using the following code to get the total number of child:
userReference = FirebaseDatabase.getInstance().getReference().child("users");
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I want to know that how I can get the the total number of child.

Try this:
userReference = FirebaseDatabase.getInstance().getReference("users");
userReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
num = dataSnapshot.getChildrenCount();
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

Related

Is there something wrong and i get 0 as value from Firebase? [duplicate]

This question already has answers here:
How to return a list from Firestore database as a result of a function in Kotlin?
(3 answers)
Closed 3 years ago.
I m trying to take a value from firebase, and always i get "0". I check my code and i cant find any error.
I used the same code in another activity and i had the correct value. Now for no reason as i didnt made any change, in both activities i cant read the value that i need
Json file:
"Ranking" : {
"Aditi" : {
"avatarUrl" : "https://i.imgur.com/S9dkvBA.png",
"score" : 60,
"userClass" : "Wizard",
"userName" : "Aditi"
},
And my code:
//Method to get the userScore from Ranking table in firebase
public void getScore() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String name = user.getDisplayName();
DatabaseReference rankingScore;
rankingScore = database.getReference("Ranking");
rankingScore.orderByChild("userName").equalTo(name)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Ranking ranking = data.getValue(Ranking.class);
totalScore = ranking.getScore();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
I expect the value of "60" but i get "0"
Update: Ranking class
public class Ranking {
private String userName;
private long score;
private String avatarUrl;
private String userClass;
public Ranking(String userName, long score, String avatarUrl, String userClass) {
this.userName = userName;
this.score = score;
this.avatarUrl = avatarUrl;
this.userClass = userClass;
}
public Ranking() {
}
public Ranking(String userName, long score) {
this.userName = userName;
this.score = score;
}
public Ranking(String userName, long score, String avatarUrl) {
this.userName = userName;
this.score = score;
this.avatarUrl = avatarUrl;
}
public String getUserClass() {
return userClass;
}
public void setUserClass(String userClass) {
this.userClass = userClass;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public long getScore() {
return score;
}
public void setScore(long score) {
this.score = score;
}
public String getAvatarUrl() {
return avatarUrl;
}
public void setAvatarUrl(String avatarUrl) {
this.avatarUrl = avatarUrl;
}
}
just add child("Aditi") in reference :-
public void getScore() {
FirebaseUser user = FirebaseAuth.getInstance().getCurrentUser();
String name = user.getDisplayName();
DatabaseReference rankingScore;
rankingScore = database.getReference("Ranking").child("Aditi");
rankingScore.orderByChild("userName").equalTo(name)
.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot data : dataSnapshot.getChildren()) {
Ranking ranking = data.getValue(Ranking.class);
totalScore = ranking.getScore();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}

Getting W/ClassMapper: No setter/field for XXX found on class

I am getting this error for every child under the parent node (GID) for Games in my Firebase json tree.
So that error message is for AwayTeam, HomeTeam, AwayScore, HomeScore, etc...Its like it did NOT map anything properly!?
The firebase structure is like the following:
Games
--- GID
----- AwayTeam
----- HomeTeam
----- AwayScore
----- HomeScore
etc...
My Adapter file is like the following:
public class PoolAdapter extends RecyclerView.Adapter<PoolAdapter.PoolViewHolder> {
public PoolAdapter(Dashboard dashboardFragment, String userID) {
this.mDashboardFragment = dashboardFragment;
mPoolRef = FirebaseDatabase.getInstance().getReference();
playerInPoolRef = mPoolRef.child("PlayerInPool").child(userID).orderByValue().equalTo(true);
playerInPoolRef.addValueEventListener(new PlayersInPoolChildEventListener());
}
private class PlayersInPoolChildEventListener implements ValueEventListener {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
getPoolData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
}
private void getPoolData(DataSnapshot dataSnapshot) {
for(DataSnapshot snapshot: dataSnapshot.getChildren()) {
String poolID = snapshot.getKey();
poolRef = mPoolRef.child("Pools").child(poolID);
poolRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
getGameData(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}
}
private void getGameData(DataSnapshot dataSnapshot) {
String gameID = dataSnapshot.child("GameId").getValue().toString();
gameRef = mPoolRef.child("Games").child(gameID);
gameRef.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
loadPlayerDashboard(dataSnapshot);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {}
});
}
private void loadPlayerDashboard(DataSnapshot dataSnapshot) {
Log.d(TAG, "*** Database snapshot: " + dataSnapshot); <-- Displays the correct Firebase information
Pools pool = dataSnapshot.getValue(Pools.class);
mPools.add(pool);
Collections.sort(mPools);
}
}
My Model class object is as follows:
public class Pools implements Comparable<Pools> {
private String _poolID;
//
private String _poolName;
private String _poolPassword;
private String _gameID;
private String _awayTeam;
private String _homeTeam;
private String _gameTime;
private String _gameDate;
public Pools() { }
public Pools(String poolID, String poolName, String gameID, String awayTeamName, String homeTeamName, String gameDate, String gameTime) {
this._poolID = poolID;
this._poolName = poolName;
//
this._gameID = gameID;
this._awayTeam = awayTeamName;
this._homeTeam = homeTeamName;
this._gameDate = gameDate;
this._gameTime = gameTime;
}
public String get_poolID() {
return _poolID;
}
public void set_poolID(String _poolID) {
this._poolID = _poolID;
}
public String get_poolName() {
return _poolName;
}
public void set_poolName(String _poolName) {
this._poolName = _poolName;
}
public String get_poolPassword() {
return _poolPassword;
}
public void set_poolPassword(String _poolPassword) {
this._poolPassword = _poolPassword;
}
public String get_gameID() {
return _gameID;
}
public void set_gameID(String _gameID) {
this._gameID = _gameID;
}
public String get_awayTeam() {
return _awayTeam;
}
public void set_awayTeam(String _awayTeam) {
this._awayTeam = _awayTeam;
}
public String get_homeTeam() {
return _homeTeam;
}
public void set_homeTeam(String _homeTeam) {
this._homeTeam = _homeTeam;
}
public String get_gameTime() {
return _gameTime;
}
public void set_gameTime(String _gameTime) {
this._gameTime = _gameTime;
}
public String get_gameDate() {
return _gameDate;
}
public void set_gameDate(String _gameDate) {
this._gameDate = _gameDate;
}
}
which has all the getters and setters so I am not sure why I am getting the error!?
I know the data is there as log log statement that you see above in my Adapter displays the following:
*** Database snapshot: DataSnapshot { key = 2019020300, value = {HomeTeam=Los Angeles Rams, GSIS=57833, GameYear=2019, isPlayed=true, hBackground=hTeam/rams.png, HomeId=29, hScore=0, GameTime=6:30, AwayId=31, aBackground=aTeam/patriots.png, SportID=1, aScore=0, Qtr=Pregame, WeekId=22, GameDate=20190203, AwayTeam=New England Patriots, SeasonType=SB} }
Does anyone know how I can resolve this!?
You need to iterate over dataSnapshot.getChildren(
for (DataSnapshot childSnapshot: dataSnapshot.getChildren()) {
Pools pool = childSnapshot.getValue(Pools.class);
}

get a value with different key Firebase Realtime DB

so i want to create a refferal code system,using firebase realtime database,but i found a difficult,how i can get all the value in key refferal?
i already have the code,but its just give me the value from my uid,
Show below:-
Query query = mDatabase.child(uid).orderByChild("refferal_status");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot movieSnapshot : dataSnapshot.getChildren()) {
UserModel movie = dataSnapshot.getValue(UserModel.class);
if (movie.getRefferal_status().equals("akmKA")) {
Toast.makeText(SpinActivity.this, movie.getRefferal_status(), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Class Model
String email;
String point;
String checkin;
String limitation;
String refferal_status;
public UserModel(){
}
public UserModel(String email,String point,String checkin,String limitation,String refferal_status){
this.email = email;
this.point = point;
this.checkin = checkin;
this.limitation = limitation;
this.refferal_status = refferal_status;
}
//setter getter here
}
so this is my database
Image
Try this !
Note:- equals expect String object .
if ("akmKA".equals(movie.getRefferal_status())) {
Toast.makeText(SpinActivity.this, movie.getRefferal_status(), Toast.LENGTH_SHORT).show();
}
Final code
Query query = mDatabase.child(uid).orderByChild("refferal_status");
query.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot movieSnapshot : dataSnapshot.getChildren()) {
UserModel movie = dataSnapshot.getValue(UserModel.class);
if ("akmKA".equals(movie.getRefferal_status())) {
Toast.makeText(SpinActivity.this, movie.getRefferal_status(), Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});

How to sum multiple values from firebase

I'm new at android programming as well as firebase. first of all look at the picture
Details image
In there I want to get all the "cost" part in total(sum). I've created the reference like that
DatabaseReference databaseBazars=firebaseDatabase.getInstance().getReference("BazarList");
now what procedure I can follow to get sum and show it in list view or in a toast message).
I've done this to get all the data from that(BazarList) node . and it perfectly showing on the listview.
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bazarList.clear();
for( DataSnapshot ds :dataSnapshot.getChildren()) {
Bazar bazar = ds.getValue(Bazar.class);
bazarList.add(bazar);
}
BazarList adapter = new BazarList(Bazar_Data_Input.this,bazarList);
listViewBazars.setAdapter(adapter);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
now, how can I get the sum part of the cost. anyone, please help me
here is the Bazar Class
public class Bazar {
String bid;
String date;
String cost;
String name;
String item;
public Bazar(){
}
public Bazar(String bid, String date, String cost, String name,String item) {
this.bid = bid;
this.date = date;
this.cost = cost;
this.name = name;
this.item= item;
}
public String getBid() {
return bid;
}
public String getDate() {
return date;
}
public String getCost() {
return cost;
}
public String getName() {
return name;
}
public String getItem() {
return item;
}
}
To solve this, please use the following code:
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bazarList.clear();
Integer total = 0;
for( DataSnapshot ds :dataSnapshot.getChildren()) {
Bazar bazar = ds.getValue(Bazar.class);
Integer cost = Integer.valueOf(bazar.getCost());
total = total + cost;
bazarList.add(bazar);
}
BazarList adapter = new BazarList(Bazar_Data_Input.this,bazarList);
listViewBazars.setAdapter(adapter);
Log.d("TAG", total + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
The output will be: 59512.
when you have bazarList with items from firebase then simply iterate over list and do sum
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
bazarList.clear();
for( DataSnapshot ds :dataSnapshot.getChildren()) {
Bazar bazar = ds.getValue(Bazar.class);
bazarList.add(bazar);
}
BazarList adapter = new BazarList(Bazar_Data_Input.this,bazarList);
listViewBazars.setAdapter(adapter);
}
double sum=getSum(); // at this moment your list have results so call getSum to get SUM
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
below is code which will do the trick
private double getSum()
{
double sum;
for( int i = 0; i < bazarList.size(); i++)
{
sum += bazarList.get(i).getCost; // Assuming Bazar class has getCost Method
}
return sum;
}
databaseBazars.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange (DataSnapshot dataSnapshot){
bazarList.clear();
for (DataSnapshot ds : dataSnapshot.getChildren()) {
Bazar bazar = ds.getValue(Bazar.class);
bazarList.add(bazar);
}
// Iterate and add all costs to sum
double sum = 0;
for (Bazar b : bazarList) {
sum += Double.parseDouble(b.getCost())
}
BazarList adapter = new BazarList(Bazar_Data_Input.this, bazarList);
listViewBazars.setAdapter(adapter);
}
#Override
public void onCancelled (DatabaseError databaseError){
}
});
mReference.addValueEventListener(object : ValueEventListener {
override fun onDataChange(snapshot: DataSnapshot) {
if (snapshot.exists()) {
for (i in snapshot.children) {
val item = i.getValue(CartItem::class.java)
cartList!!.add(item!!)
}
var sum = 0.0
for (itm: CartItem in cartList!!) {
sum += itm.itemPrice.toDouble()
}
total_value.text = sum.toString()
//Initialise my adapter
mRecyclerView.adapter = CartItemsAdapter(applicationContext, cartList!!)
}
}
override fun onCancelled(error: DatabaseError) {
}
})

How is the data returning from Firebase Android?

I get each profile back as objects and put them into an array list. The first println shows size as 1 then the second one shows the size as 0. How is this possible?... My Profile class has getters for each attribute and an empty Profile constructor.
// Initialize Profiles Array, global variable in my project
ArrayList<Profile> profileObjects = new ArrayList<>();
// GET FIREBASE PROFILE DATA, PUT INTO ARRAY
ref.child("Users").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot child : dataSnapshot.getChildren()){
Profile profiles = child.getValue(Profile.class);
profileObjects.add(profiles);
}
System.out.println("GETTTINGGGGG BACKKKKKKKKKKKKKKKKKKKKKKK 1: " + profileObjects.size());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
System.out.println("GETTTINGGGGG BACKKKKKKKKKKKKKKKKKKKKKKK 2: " + profileObjects.size());
Picture of my data in Firebase:
you can get all user's data then get "pic" from it or you can get only "pic" reference.
ref.child("Users").child(userId).addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
// to get all user object ,then you can get pic url from it by calling user.getPic() for example
Usermodel user = dataSnapshot.getValue(Usermodel .class);
String picUrl = user.getPic();
// or you can get "pic" value only
String picUrl = dataSnapshot.child("pic").getValue(String.class);
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
your UserModel class could be like this
public class UserModel {
public UserModel() {
}
String name, age, gender, pic;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic;
}
}
you get null caue of
String picUrl = dataSnapshot.child("Uid").child("pic").toString();
where Uid is Just String not variable
you need to use
for (DataSnapshot child : dataSnapshot.getChildren())
{
// each child is user
// if you have use model do this
Usermodel um = child.getValue(Usermodel .class);
String picurl = um.getpicurl();
}

Categories

Resources