I have 2 different fragments: one with an EventListener that checks for changes in Firebase, this is the code:
dbUsers.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
User user = dataSnapshot.getValue(User.class);
favo_team_view = (TextView) myView.findViewById(R.id.favo_team_textview);
if(!(user.getTeam() == null)) {
favo_team_view.setText("Your favourite team is: " + user.getTeam());
} else {
favo_team_view.setText("Your favourite team is: " );
}
}
@Override
public void onCancelled(@NonNull DatabaseError databaseError) {
}
});
And another fragment that deletes an entry in the database, and starts an intent to start the SignInActivity (Both fragments are part of the MainActivity) ; this is the code
Button deleteUserButton = myView.findViewById(R.id.delete_user);
deleteUserButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String uid = auth.getUid();
final DatabaseReference dbUsers = FirebaseDatabase.getInstance().getReference("users").child(uid);
auth.getCurrentUser().delete().addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if(task.isSuccessful()){
dbUsers.setValue(null);
signOut();
}else{
displayMessage(getString(R.string.user_deletion_error));
}
}
});
}
});
private void signOut(){
Intent signOutIntent = new Intent(myView.getContext(), SigninActivity.class);
startActivity(signOutIntent);
//finish();
}
The code works in that the entry in the DB gets deleted. But my app crashes, and the stacktrace tells me:
Java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.User.getTeam()' on a null object reference at com.ChooseTeam$1.onDataChange
Why does it do that? I don't understand why the Listener still checks for data-changes (that fragment is not active/open when I delete the database)
Thank you
PS: realized i can't check a string on == null, just thought I'd give it a shot. Same thing without the if statement ofcourse