Fixed null pointer dereference bugs in buildDatabase and flush methods