I want to calculate the sum of all rating values(float) that is in the nodes of Firebase database and wants to show in the text box.
Firebase Database
Firebase DATABASE Preview
Rating values i want to retrieve. I want sum of all the rating values and save that sum value in the text box.
Here is what i done
Database Class
public class databaseReview {
String description,name,userImage;
String rating;
public databaseReview(){
}
public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
public databaseReview(String rating, String description) {
this.rating = rating;
this.description = description;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getuserImage() {
return userImage;
}
public void setuserImage(String userImage) {
this.userImage = userImage;
}
}
Java Class
DatabaseReference dataReference =
FirebaseDatabase.getInstance().
getReference().child("Feedbacks").child(name);
dataReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for( DataSnapshot ds :dataSnapshot.getChildren()) {
databaseReview data = ds.getValue(databaseReview.class);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {}
});
Assuming that the Feedbacks node is a direct child of your Firebase root and the name variable has its value as Abasyn University Islamabad, to count all the ratings, please use the following code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference nameRef = rootRef.child("Feedbacks").child(name);
ValueEventListener eventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double count = 0;
for(DataSnapshot ds : dataSnapshot.getChildren()) {
double rating = ds.child("rating").getValue(Double.class);
count = count + rating;
}
Log.d("TAG", count + "");
}
#Override
public void onCancelled(DatabaseError databaseError) {}
};
nameRef.addListenerForSingleValueEvent(eventListener);
But be aware, this will work only if the raiting property is stored in your database as a double. Your screenshot is correct but your model class shows:
String rating;
Related
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) {
}
});
I am developing an android based app using Firebase as backend server. I have designed the Structure of the app in the following manner:
Project Name
|_ Products
|_ groups
|_ 1BME
|_ members
|_ -K4usWDhtiw4U
|_ Custom Object
|_ -K4uscDHwYsXHs
|_ Custom Object
The Custom Object is:
package com.app.shubhamjhunjhunwala.heritagecompanion_students;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
/**
* Created by shubham on 23/01/17.
*/
public class UserDetails {
UserDetails() {}
public String name;
public String email;
public String password;
public String phone;
public String roll;
public String department;
public String year;
public String section;
public String dpDownloadUri;
public UserDetails(String name, String email, String password, String phone, String roll, String department, String year, String section, String dpDownloadUri) {
this.name = name;
this.email = email;
this.password = password;
this.phone = phone;
this.roll = roll;
this.department = department;
this.year = year;
this.section = section;
this.dpDownloadUri = dpDownloadUri;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getYear() {
return year;
}
public void setYear(String year) {
this.year = year;
}
public String getSection() {
return section;
}
public void setSection(String section) {
this.section = section;
}
public String getDpDownloadUri() {
return dpDownloadUri;
}
public void setDpDownloadUri(String dpDownloadUri) {
this.dpDownloadUri = dpDownloadUri;
}
}
My intention is to get the user details under members child under 1BME under Groups child. So for this, I use the Following code in my program:
mDatabase = FirebaseDatabase.getInstance();
mGroupMembersDatabaseReference = mDatabase.getReference().child("groups").child(groupRoll).child("members");
mGroupMembersDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
UserDetails users = dataSnapshot.getValue(UserDetails.class);
Toast.makeText(GroupChatActivity.this, users.getRoll(), Toast.LENGTH_SHORT).show();
if (!users.getRoll().equals(senderRoll)) {
Toast.makeText(GroupChatActivity.this, users.getName(), Toast.LENGTH_SHORT).show();
mRecieverDatabaseReference = mRecieverDatabaseReference.child(users.getRoll()).child("groups").child(groupRoll);
Query query1 = mRecieverDatabaseReference.orderByChild("roll").equalTo(groupRoll);
query1.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for (DataSnapshot dataSnapshot1 : dataSnapshot.getChildren()) {
dataSnapshot1.getRef().child("state").setValue("unread");
dataSnapshot1.getRef().child("timeID").setValue(timeID);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Messages message = new Messages(messageText, time, senderRoll, name, chatName, groupRoll, mState, messageType, "");
mRecieverDatabaseReference.push().setValue(message);
mRecieverDatabaseReference = mDatabase.getReference().child("chats");
}
}
#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) {
}
});
In this code String groupRoll = "1BME"
But when I run this code and debug it, I find that it never enters onChildAdded(). So please help me. The app isn't moving forward because of this.
Thank You.
First of all your DatabaseReference is wrong. To get data from a member please use this code:
mGroupMembersDatabaseReference = mDatabase.getReference().child("groups").child(groupRoll).child("members").child(memberId);
In which the memberId is unique id generated by the push() method.
Second, you don't need to use addListenerForSingleValueEvent to change a value. Is wrong to use setValue() method on a DataSnapshot. You can use setValue() directly on your reference. Hope it helps.
try this
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
UserDetails users = snapshot.getValue(UserDetails.class);
//...
}
My code is as show below:
mFirebaseDatabase = mFirebaseInstance.getReference();
mFirebaseDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
allText.setText(dataSnapshot.child("58ca237b2e2c211dc0c7ed9").child("order_status").getValue(String.class));
Log.d(TAG, "onDataChange: " + dataSnapshot.hasChild("58ca237b2e2c211dc0c7ed9"));
Log.d(TAG, "onDataChange: next " + dataSnapshot.getValue().equals("58ca237b2e2c211dc0c7ed9"));
for (DataSnapshot child : dataSnapshot.getChildren()) {
Log.d(TAG, "onDataChange for: " + child.toString());
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "onCancelled: ");
}
});
The response that I am getting in log is as shown below:
onDataChange for: DataSnapshot { key = 58ca237b2e2c211dc0c7ed9, value = {order_status=2} }
Here, I want to read order_status=2, but I am unable to do it. How can I do that?
My firebase schema is as show below:
You can Send/Receive Data from FireBase following way:
Send data to FireBase
EmpInfo empInfo = new EmpInfo();
empInfo.setName(mEditTextName.getText().toString());
empInfo.setAge(mEditTextAge.getText().toString());
empInfo.setMobile(mEditTextMobileNo.getText().toString());
empInfo.setCity(autoCompleteTextView.getText().toString());
databaseReference.child("Emp_Info").setValue(empInfo);
Get Data from FireBase
databaseReference.child("Emp_Info").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Log.d(TAG,"onDataChages invoked ="+dataSnapshot.toString());
//Getting the data from snapshot
EmpInfo empInfo = (EmpInfo)dataSnapshot.getValue(EmpInfo.class);
mTextName.setText(mTextName.getText()+" : "+empInfo.getName());
mTextAge.setText(mTextAge.getText()+" : "+empInfo.getAge());
mTextMobileNo.setText(mTextMobileNo.getText()+" : "+empInfo.getMobile());
mTextCity.setText(mTextCity.getText()+" : "+empInfo.getCity());
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
Model class
public class EmpInfo {
public String name;
public String age;
public String mobile;
public String city;
public EmpInfo(){
}
public EmpInfo(String name, String age, String mobile,String city) {
this.name = name;
this.age = age;
this.mobile = mobile;
this.city = city;
}
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 getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}
Hope It will help you !
Create Model of result that you are expecting and then simply do like this, you can manipulate the code that works for you
public static class Post {
public String author;
public String title;
public Post(String author, String title) {
this.author = author;
this.title = title;
}
//Default Constructor
public Post {
}
//Setter and Getter below
-----
// Get a reference to our posts
final FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference ref = database.getReference("server/saving-
data/fireblog/posts");
// Attach a listener to read the data at our posts reference
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
Post post = dataSnapshot.getValue(Post.class);
System.out.println(post.get(------));
}
#Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getCode());
}
});
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();
}
I use firebase to store data , but I could not get the list of data
from firabse ,Specifically I want to get arraylist of person object.
here is the class person
public class Person {
private String name;
private String username;
public Person() {
}
public Person(String name, String username) {
this.name = name;
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
and here is data structure
You can fetch the data with any of the event listeners. Here is with child event listener.
List<Person> persons = new ArrayList<>();
ChildEventListener listener = new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Person person = dataSnapshot.getValue(Person.class);
persons.add(person);
}
#Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
Person person = dataSnapshot.getValue(Person.class);
persons.remove(person);
}
#Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
};
FirebaseDatabase.getInstance().getReference().child("persons").addChildEventListener(listener);
Ugur B answers also correct one. Here,You can also fetch firebase data by using the ValueEventListener too...
ArrayList<String> arrayListVal = new ArrayList<String>();
fbref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
Person person = postSnapshot.getValue(Person.class);
//Adding it to a ArrayList
arrayListVal.add(person);
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("Failed to fetch data: " + firebaseError.getMessage());
}
});