Fix possible NPE

Fix #1820, fix #1821, fix #1823