1
I have a method that I want to check at all times in the database if a field of the child node is modified (in this case, the "status" field), when it is changed, I want the text on the android screen to be modified. I am able to change the text, but when I exit and enter the screen again the message disappears (even when the status in the database is changed). Code:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
circleImageViewUser = findViewById(R.id.circleImageViewUser);
txtOcorrencias = findViewById(R.id.txtOcorrencias);
txtStatus = findViewById(R.id.txtStatus);
txtPendencias = findViewById(R.id.txtPendencias);
txtSaudacao = findViewById(R.id.txtSaudacao);
Toolbar toolbar = findViewById(R.id.toolbarPrincipal);
setSupportActionBar(toolbar);
recuperarUsuario();
recuperarFotoUsuario();
verificaStatusOcorrencia();
}
public void verificaStatusOcorrencia() {
String idUsuario = UserFirebase.getDadosUsuarioLogado().getIdUsuario();
usuarioRef = firebaseRef.child("ocorrencias").child(idUsuario);
usuarioRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot snapshot : dataSnapshot.getChildren()) {
Ocorrencia ocorrencia = snapshot.getValue(Ocorrencia.class);
if (ocorrencia.getStatus() == "1") {
txtStatus.setText(Ocorrencia.A_CAMINHO);
txtStatus.setTextColor(Color.MAGENTA);
txtStatus.setTextSize(16);
} else if (ocorrencia.getStatus() == "0") {
txtStatus.setText(Ocorrencia.AGUARDANDO);
txtStatus.setTextColor(Color.RED);
txtStatus.setTextSize(16);
} else if (ocorrencia.getStatus() == "2"){
txtStatus.setText(Ocorrencia.OK);
txtStatus.setTextColor(Color.GREEN);
txtStatus.setTextSize(17);
}
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
}
Database:
Your code will always show the status of the last occurrence of this user (not necessarily the last registration, but the last one at the end of the foreach because they are not using any sort). If you want to show the status of a specific occurrence, you must add the occurrence id in the reference and remove the foreach from the code. You can also set which occurrences you want to check inside the foreach.
– Itapox