Add null checks for database connection

Add null checks for SQLiteDatabase connection to test if a connection is
actually created. Also only close the connection if it is not null.