Calculate Sum of values from node Firebase - java

I am getting all quantity price. But I don't know how to add them all and get it under one string. Can someone pls help
FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance();
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference databaseReference = mFirebaseDatabase.getReference().child("cart").child(uid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()) {
Log.d("dasdasdasdad", String.valueOf(dataSnapshot));
String quantityprice = (String) dataSnapshot.child("quantityprice").getValue();
Log.d("quantityprice", String.valueOf(quantityprice));
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
In here i am getting all quantityprice value in Log
i.e:- 130,55,150
But i dont know how to add them all and get it under one string.
Anyhelp would be appreciated.
I have tried this too
DatabaseReference databaseReference = mFirebaseDatabase.getReference().child("cart").child(uid);
databaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot: snapshot.getChildren()) {
Log.d("dasdasdasdad", String.valueOf(dataSnapshot));
Integer total = 0;
String quantityprice = (String) dataSnapshot.child("quantityprice").getValue();
Log.d("quantityprice", String.valueOf(quantityprice));
int price = Integer.valueOf(quantityprice);
total =+ price;
Log.d("total",total); }
but total is shown different all time.
This is Log
D/quantityprice: 130
D/total: 130
D/quantityprice: 55
D/total: 55
D/quantityprice: 150
D/total: 150

To solve this problem, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference productsRef = db.child("card").child(uid);
productsRef.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
double total = 0.00;
for (DataSnapshot ds : task.getResult().getChildren()) {
String quantityPrice = ds.child("quantityprice").getValue(String.class);
total += Double.parseDouble(quantityPrice);
}
Log.d("TAG", "total: " + total);
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
total: 335.00
The key to solving this problem is to parse the String value from the database to a double. Remember, if you need numbers, it's best to store them in the database as numbers and not as String values.

Related

On Android, how do you get the data from an email address in Firebase, then access the child, and from there you access the other Firebase data?

The following file explains better what I really mean. It's a screenshot of data sent from a dummy user in Firebase:
The code:
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users");
// ref.addValueEventListener(new ValueEventListener() {
ref.orderByChild("Email").equalTo("testing3#testing.com").addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot datas : dataSnapshot.getChildren()) {
String key = datas.getKey();
DatabaseReference ref = FirebaseDatabase.getInstance().getReference().child("Users").child(key);
Toast.makeText(getApplicationContext(), key, Toast.LENGTH_LONG).show();
ref.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
String name = dataSnapshot.child("Name").getValue().toString();
String state = dataSnapshot.child("State").getValue().toString();
String stateRegion = dataSnapshot.child("StateRegion").getValue().toString();
String telephone = String.valueOf(dataSnapshot.child("Telephone").getValue());
nameEditText.setText(name);
stateEditText.setText(state);
stateRegionEditText.setText(stateRegion);
telephoneEditText.setText(telephone);
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
});
Please, can some person help?
More information about data stored in the Firebase:
Because I cannot see a more detailed database schema of yours, I assume that all those user objects are direct children under your Users node, and also assuming that you want to find the user that has the Email set to testing3#tesing.com, to display his particular details, please use the following lines of code:
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = db.child("Users");
Query queryUsersByEmail = usersRef.orderByChild("Email").equalTo("testing3#testing.com");
queryUsersByEmail.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String name = ds.child("Name").getValue(String.class);
Log.d("TAG", name);
String state = ds.child("State").getValue(String.class);
Log.d("TAG", state);
String stateRegion = ds.child("State Region").getValue(String.class);
Log.d("TAG", stateRegion);
String telephone = ds.child("Telephone").getValue(String.class);
Log.d("TAG", telephone);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Never ignore potential errors!
}
}
});
The result in the logcat will be:
Paul SMith
Rio de Janeiro
Rio de Janeiro
(00)00000-0000

How to get value in Firebase

My database:
enter image description here
I got "Code". I try to get "ClassID" (Ex: Code=1235, I want a String ClassID= "12"):
Here my code:
private void checkCode(){
String userCode = inputCode.getText().toString().trim();
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("Assignment");
Query checkCode = reference.orderByChild("Code").equalTo(userCode);
checkCode.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
if(snapshot.exists()){
String classID; // I think here
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
How to do that?
If you want to search the database for all objects that have the "Code" property set to "1235" and then get the value of "classID", please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference assignmentRef = rootRef.child("Assignment");
Query codeQuery = assignmentRef.orderByChild("Code").equalTo("1235");
codeQuery.get().addOnCompleteListener(new OnCompleteListener<DataSnapshot>() {
#Override
public void onComplete(#NonNull Task<DataSnapshot> task) {
if (task.isSuccessful()) {
for (DataSnapshot ds : task.getResult().getChildren()) {
String classID = ds.child("classID").getValue(String.class);
Log.d("TAG", "ClassID: " + classID);
}
} else {
Log.d("TAG", task.getException().getMessage()); //Don't ignore potential errors!
}
}
});
The result in the logcat will be:
ClassID: 12
The exact value you are looking for. Remember that each time you query the database, you need to loop through the results using .getChildren() method, in order to get the results.

Firebase Realtime Database not displayed when retriving to textviews in Android

onCreate() method is never executed. I just want to take the below data to 4 TextViews. "Detail" is the model class.
No errors are shown when running the app.
view_temp is an activity.
this is firebase realtime db
this is the java class
`public class view_temp extends AppCompatActivity {
private view_temp viewTemp;
public Detail detail;
private TextView roomtemp, roomhuminity, bodypulse, bodytemp;
private DatabaseReference mDatabase;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_temp);
mDatabase = FirebaseDatabase.getInstance().getReference("heat-stroke-device");
roomtemp = (TextView) findViewById(R.id.txt_room_temp);
roomhuminity = (TextView) findViewById(R.id.txt_huminity_temp);
bodypulse = (TextView) findViewById(R.id.txt_body_pulse);
bodytemp = (TextView) findViewById(R.id.txt_body_temp);
mDatabase.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot postSnapshot : snapshot.getChildren()) {
detail = postSnapshot.getValue(Detail.class);
String rtemp = detail.getRoomtemp();
String rhumidity = detail.getRoomhumidity();
String bpulse = detail.getBodypulse();
String btemp = detail.getBodytemp();
roomtemp.setText(rtemp);
roomhuminity.setText(rhumidity);
bodypulse.setText(bpulse);
bodytemp.setText(btemp);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
System.out.println("The read failed: " + databaseError.getMessage());
}
});
}
}`
There is no need to add the name of the project in the getReference() method. To get those names and the corresponding values correctly, please use the following lines of code:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String name = ds.getKey();
double value = ds.getValue(Double.class);
Log.d("TAG", name "/" + value);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
RoomHumi/86.0
RoomTemp/30.8
bodyPulse/126.0
bodyTemp/29.0
If the keys are always fixed, then simply use:
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
double roomHumi = dataSnapshot.child("RoomHumi").getValue(Double.class);
Log.d("TAG", "RoomHumi" "/" + valueroomHumi);
double roomTemp = dataSnapshot.child("RoomTemp").getValue(Double.class);
Log.d("TAG", "RoomTemp" "/" + roomTemp);
double bodyPulse = dataSnapshot.child("bodyPulse").getValue(Double.class);
Log.d("TAG", "bodyPulse" "/" + bodyPulse);
double bodyTemp = dataSnapshot.child("bodyTemp").getValue(Double.class);
Log.d("TAG", "bodyTemp" "/" + bodyTemp);
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore potential errors!
}
};
rootRef.addListenerForSingleValueEvent(valueEventListener);
And you'll have the same result in the logcat.
Just change your line
mDatabase = FirebaseDatabase.getInstance().getReference("heat-stroke-device");
to
mDatabase = FirebaseDatabase.getInstance().getReference();
Note: You do not need to put your database name into reference.

how to get the name of parent A+ for this code?

I am unable to access this parent node using that code.
public void onComplete(#NonNull Task<AuthResult> task) {
if (!task.isSuccessful()) {
Toast.makeText(LoginActivity.this,"Login error", Toast.LENGTH_SHORT).show();
} else {
String user = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference mRef = FirebaseDatabase.getInstance().getReference();
final Query userQuery = mRef.orderByChild(user);
userQuery.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, #Nullable String s) {
map.clear();
String myParentNode = dataSnapshot.getKey();
for (DataSnapshot child: dataSnapshot.getChildren()) {
String key = child.getKey().toString();
String value = child.getValue().toString();
map.put(key, value);
}
Intent intent = new Intent(LoginActivity.this, UserMapActivity.class);
intent.putExtra("bloodType",myParentNode);
startActivity(intent);
}
}
}
}
i want to get the highlighted parent from the underline child in every session
To get A+, please use the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference usersRef = rootRef.child("Users");
Query query = usersRef.orderByChild(uid).equalTo(true);
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Log.d(TAG, ds.getKey());
//Do what you need to do with your key
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
query.addListenerForSingleValueEvent(valueEventListener);
The output in the logatcat will be:
A+

Retrieving nested data with ids in firebase?

I am trying to retrive messages from Message node. Each message in messages has an Id. The final result I am trying to achieve is just the message for each user or is there ant better way to store the data as I don't need the key for storing messages, but when I don't include the key the old data gets deleted.
structure of my data
DatabaseReference dbfriends= FirebaseDatabase.getInstance().getReference().child("Users");
dbfriends.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if(dataSnapshot.exists())
{
for (DataSnapshot productSnapshot:dataSnapshot.getChildren())
{
Log.i("IDDD",productSnapshot.toString());
Log.i("IDDDDDDDD",productSnapshot.child("Messages").getValue().toString());
String friend=productSnapshot.child("Username").getValue().toString();
Log.i("This is friend",friend.toString());
friends.add(friend);
}
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference messagesRef = rootRef.child("Users").child(uid).child("Messages");
ValueEventListener valueEventListener = new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
String sender = ds.child("sender").getValue(String.class);
String message = ds.child("message").getValue(String.class);
Log.d(TAG, sender + ": " + message);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
Log.d(TAG, databaseError.getMessage()); //Don't ignore errors!
}
};
messagesRef.addListenerForSingleValueEvent(valueEventListener);
The result in your logcat will be:
Jeffy: Alic how r you?
Jeffy: Alic how r you?
If you also need the key, simply use:
String key = ds.getKey();

Categories

Resources