问题
I am trying to get a double from firebase object using dataSnapshot but each time I try to, I'm getting an error saying that java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Double and when I try to maybe Cast it to a Long just to observe what's gonna happen I get this Error java.lang.ClassCastException: java.lang.Double cannot be cast to java.lang.Long, so in short the error is vice versa. This is the code I'm using to get my total in Firebase dataSnapshot:
mDatabaseReference.child(mAuth.getCurrentUser().getUid()).addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if (!isPrinted) {
System.out.println("Children" + dataSnapshot.getChildrenCount());
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Double price = (Double) snapshot.child("total").getValue();
System.out.println("Price: " + String.valueOf(price));
}
isPrinted = true;
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
and this is the code I'm using to save the total on firebase:
double total = holder.quantity * price;
dataSnapshot.child(code).child("total").getRef().setValue(total);
I'm looking to retrieve the total from firebase using Double but it gives me the ClassCastException. Please help with a solution.
I also tried looking here for a solution but did not find anything
This is my FirebaseDatabase where I'm querying from:
回答1:
I think I can see the problem from your Database Screenshot. You have one total node's value as "5.16". While, another total's value is "0" (I also assume that you have a lot more total nodes with values as "0").
So, you're getting a ClassCastException no matter what you do because "5.16" is treated as a Double, while "0" is treated as a Long - and you're retrieving both in the same query.
The simplest solution is to change your "0" to "0.0". This would make all total nodes hold Double values. Then, you just have to call the following to retrieve the value :-
Double price = (Double) snapshot.child("total").getValue();
回答2:
It is because 0 is treated and stored as Long, not Double. To make code work in both cases, do:
double val = 0;
Number num = (Number) snapshot.child("total").getValue();
if (num != null) {
val = num.doubleValue();
}
来源:https://stackoverflow.com/questions/46233995/get-double-from-firebase