Reputation: 19
I am trying to display data in my database but I'm having a problem doing so. The data I'm trying to display is saved as "total" and it is saved as an int. I have tried saving it as a string and double but still no luck. Ideally, I would like to display the total then display a message if the total is over the value 9. This is what I have so far.
public class Results extends AppCompatActivity {
private DatabaseReference mDatabase;
private FirebaseAuth fAuth;
private Button btn;
private TextView userR;
private TextView num;
private FirebaseUser currentUser;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_results);
userR = (TextView) findViewById(R.id.userResults);
btn = (Button) findViewById(R.id.generate);
fAuth = FirebaseAuth.getInstance();
currentUser = fAuth.getCurrentUser();
mDatabase = FirebaseDatabase.getInstance().getReference().child("FAQ");
}
@Override
public void onStart() {
super.onStart();
ValueEventListener scoreListener = new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
faqinputs FAQInputs = dataSnapshot.getValue(faqinputs.class);
userR.setText(FAQInputs.getTotal());
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
};
mDatabase.addValueEventListener(scoreListener);
}
}
"total" is saved in a "FAQ" node which is saved under a "User"
The data structure is as follows: This is a screenshot some data stored under set nodes
The below data is the code I used to create the FAQ node.
private void sendScoreData() {
String currentUserID = fAuth.getUid();
faqinputs FAQInputs = new faqinputs(questionOne, questionTwo, questionThree, questionFour, questionFive, questionSix, questionSeven, questionEight, questionNine, questionTen, total);
mDatabase.child("Users").child(currentUserID).push().child("FAQ").setValue(FAQInputs);
}
}
Upvotes: 1
Views: 96
Reputation: 138824
To get the value of the total
property, you have to add all node names in your reference, like in the following lines of code:
String uid = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
DatabaseReference totalRef = rootRef.child("Users").child(uid).child("-M4YRj8nbobkuKurbHqC").child("FAQ").child("total");
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int total = dataSnapshot.getValue(Integer.class);
Log.d("TAG", "total: " + total);
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
Log.d("TAG", databaseError.getMessage()); //Don't ignore errors!
}
};
totalRef.addListenerForSingleValueEvent(valueEventListener);
The result in the logcat will be:
total: 15
I see the total to be a number, however, if you save it as a String, use this line:
String total = dataSnapshot.getValue(String.class);
Upvotes: 1