When the Bible calls David a man after God's own heart, it doesn't mean that he was "special" to God in a perverse showing-of-favoritism kind of way. Nor does it mean that David got away with personal sins because God liked him better than other people. Nor does it mean that David was this perpetual harp-playing, tree-hugging, sheep-tending innocent-of-heart boy.
David sinned grievously. MANY times. In MANY ways. He admitted those very words - "I have sinned grievously." And God refused to allow David to build the Temple because David has too much blood on his hands as a military man. 1 Chronicles 22:8
He was a lousy husband and a worse father. His family - especially his children - were more dysfunctional because of David, their father, than was Jacob's family.
Many people suffered because of David's own personal sins. The punishment that the people had to bear when David numbered them, the men, boys, and male animals living on Abigail's property who almost lost their lives because of David's pride and temper, Uriah, Bathsheba, David's children suffering from his neglect of discipline, and Michal, who became very bitter towards David, as his wife because after she helped him escape from her father - she doesn't see him for a long time and when she is finally reunited, she had already been forced to live with another man she didn't love and David has other wives.
Then why does David get that prized title, "a man after God's own heart?"
Because of a couple of things.
It's in part because of David's devotion - his love and obedience to God and his fierce dependence ON God. That's a big part of it.
Another big part of it is because whenever God "called David out" on his personal and wicked sins - his passionate temper, his fleshly passions, and his pride - David immediately and without hesitation repented with MUCH grief.
King David mourned over his personal sins and their affront to God like no other person seen in the Bible. His own sins made him sick. And when confronted with them, he turned away from them and acknowledged his sin before a Holy God.
Being a man after God's own heart didn't make him special. It made him a sinful man who was willing to allow God to purge the sin away from him and submitted to the chastisement of God with as much abandon as he did the love of God.