Fix ArrayIndexOutOfBounds and avoid NPE