Solving NPE but not overusing memory