I have previously searched for solutions to this but I'm having problems understanding exactly how I'm getting a NullPointerException. My goal is to set a message for a textView
, but the app crashes when it happens. This is the error:
java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.String com.okimin.flashchatnewfirebase.Post.getMessage()' on a null object reference
The variables:
private FirebaseUser user;
private FirebaseAuth mAuth;
private DatabaseReference mDatabaseReference;
Initializing them:
mAuth = FirebaseAuth.getInstance();
mDatabaseReference = FirebaseDatabase.getInstance().getReference();
user = FirebaseAuth.getInstance().getCurrentUser();
Where the problem happens:
final String iD= user.getUid();
mDatabaseReference.child("messages").child(iD).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
Post postIt = new Post();
postIt.setMessage(dataSnapshot.getValue(Post.class).getMessage()); // Where the problem happens
mtextview.setText(postIt.getMessage());
}
}
Post class:
public class Post {
private String message;
private String author;
public Post(){
}
public Post(String message, String author) {
this.message = message;
this.author = author;
}
public String getMessage() {
return message;
}
public String getAuthor() {
return author;
}
public void setMessage(String message) {
this.message = message;
}
public void setAuthor(String author) {
this.author = author;
}
}
The structure:
Everything works until I get an actual value.