I try to implement the Observer pattern in one of my activities and face the following exception when calling notifyObservers:
java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at java.util.Observable.notifyObservers(Observable.java:131)
at models.database.User.setPending(User.java:137)
My implementation is pretty straightforward: the model User is the observable and the activity is the observer (which shouldn't matter because the activity code is never reached). My goal is to be notified about every change in the field's properties.
This is the relevant part in User class:
public class User extends Observable implements Parcelable {
private boolean pending;
public void setPending(boolean pending) {
synchronized (this) {
this.pending = pending;
}
setChanged();
notifyObservers(this);
}
}
Is there any flaw in my implementation or in my understanding here? I have no idea what's wrong and I prefer to solve it rather than move to the RX implementation.
EDIT: This is the MainActivity code, which is never reached:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Get session variables from previous activity (LoginActivity/SplashActivity)
user = getIntent().getExtras().getParcelable(getString(R.string.e_user)); //Receiving user from previous activity, assured to be non-null
//Add observer on user, so we'll be able to update drawer in case of modification
user.addObserver(this);
}
@Override
public void update(Observable observable, Object o) {
drawerBuilder.setUser(user);
}
I continued digging and found out that Retrofit, the library which I use to make HTTP requests, doesn't call constructors at all, and I didn't face this error so far because I receive
UserinLoginActivity/SplashActivityand passes it toMainActivityusing extras, thus using theUser(Parcel in)constructor (the only one I had).Adding an empty constructor to the
Userclass solved the issue. However, I still don't understand how no exception was thrown previously by Retrofit.