Prevent NPEs in codes

The PR fixes possible NPE errors discovered by FindBugs