I have a question I hope and help me I want to show a data of firebase in a textview on Android but I really have no idea how to do it, the specific data is like "Value "
To do it do the following
DatabaseReference ref = FirebaseDatabase.getInstance().getReference();
ref.child("Persona").child("Valor").addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
int valor = dataSnapshot.getValue(Integer.class);
textView.setText(String.valueOf(valor);
}
@Override
public void onCancelled(DatabaseError databaseError) {
System.out.println("Fallo la lectura: " + databaseError.getCode());
}
});
First we create the reference to where the value is, and then we go and look for that value, we keep it in a variable of integer type int and then we put it in TextView
with setText
, we use String.valueOf
since is an integer and setText
needs to pass a String.
Each time that value is modified, your TextView
will be modified with that value in real time.
Note: remember that the Firebase rules decide who has access to the data, so if it does not work or it does not read to you, it is not the code but your rules, you can use the following ones to debug for the moment and then in production you change them by more secure rules
Only debug. If you are not going to use authentication and it does not matter who reads or writes the database, you can leave them like this
{
"rules": {
".read": true,
".write":true
}
}
Remember that addValueEventListener ... like other listeners in Firebase they are asynchronous, this means they work in the background asking for the data and when they have it, they just do the action that find within
onDataChange
so put thesetText
out ofonDataChange
would not put anything since you can not access that value before being requested.