Fix potential NPE and UI thread issue