In 1 Samuel 13:14, Samuel warns King Saul, "But now your kingdom shall not endure. The Lord has sought out for Himself a man after His own heart..."
Here, he meant David, who is also the subject of Acts 13:22, when God says, "I have found in David the son of Jesse a man after my heart, who will do all my will."
1 Kings 11:4 says that David's heart was "wholly true to the Lord."
There is no question that David was a man of God. Scripture tells us this.
But David, like all other men (and women) of God, wasn't perfect. Now king of Israel, David sees a beautiful woman, Bathsheba. He asks about her and finds out that she is married. Not only is she married, but her husband Uriah is one of David's best warriors. This doesn't deter David. He sends for her, she comes to his house, they have sex, and she gets pregnant.
David tries to cover up his sin. He brings Uriah home from battle and tries to convince him to "go down to his house" and spend some time with Bathsheba so that Uriah will think the child is his own. Uriah refuses to go, and David sends him back into battle. David then orders that Uriah be sent to the front of the battle and that those around him will draw back, leaving Uriah to die.
And so it was. Bathsheba mourned her husband, and David took her as his own wife.
"But the thing that David had done displeased the Lord."
God sends Nathan the prophet to come and rebuke David.
"Why have you despised the word of the Lord, to do what is evil in his sight? You have struck down Uriah the Hittite with the sword and have taken his wife to be your wife."
David probably thought he got away with it until this point. His sin would go undetected, he would probably eventually repent, and life would go on.
Nathan tells David that there are going to be public consequences for his sin, that God will later bring calamity on him from within his own family:
"For you did it secretly, but I will do this thing before all Israel and before the sun."
David admits, "I have sinned against the Lord."
Nathan says, "The Lord also has put away your sin; you shall not die." Grace! Forgiveness! David's sin is put away.
But Nathan continues, "Nevertheless, because by this deed you have utterly scorned the Lord, the child who is born to you will die."
And so it was.
Later, long after David had died, God says to David's son Solomon (who was king after David and eventually turned away from the Lord), "Since you have not kept my covenant and my statutes, I will tear the kingdom from you. Yet for the sake of David your father I will not do it in your days. I will not tear away all of the kingdom, but I will give one tribe to your son, for the sake of David my servant."
God demonstrates his lasting love and forgiveness of David here. He demonstrates his grace. This grace is neither contradicted by nor canceled out by the negative consequences of David's sin. God does not withhold discipline in favor of grace, and God does not withhold grace in favor of discipline.