Yahweh did that because David had always done what pleased Yahweh and because David had always obeyed Yahweh. The only time when he disobeyed Yahweh was when he caused Uriah to be killed.