Added necessary null checks to prevent NPEs