You can prevent this kind of error to happen by
never assuming that an object has been correctly initialized before using it (i.e.,
always check for a null value before using any class).
In code, here's a small example describing the general idea:
if (myobject != null) {
}
else {
}