Fix possible NPE and crashes