Unfortunately, that phrase is frequently misused and even misunderstood. At issue is this: Precisely when in David's life did God regard him as a man after His own heart?
The answer: 1 Sam. 13:14 and Acts 13:22.
1 Sam. 13 recounts the story of Saul's choice to offer sacrifice to God without a priestly representative present. Because he violated God's word and did not wait for Samuel to be present, Samuel tells him,
You have acted foolishly; you have not kept the commandment of the LORD your God, which He commanded you, for now the LORD would have established your kingdom over Israel forever. But now your kingdom shall not endure. The LORD has sought out for Himself a man after His own heart, and the LORD has appointed him as ruler over His people, because you have not kept what the LORD commanded you.There it is! David was a man after God's own heart, BEFORE he was anointed king of Israel. It was the shepherd boy David of whom God said he is a man after my heart. God did not say this about David after his adultery with Bathsheba. This was not an end-of-life analysis of David. It was the early, pre-Goliath David who was a man after God's own heart.
Acts 13:22 expands on this passage a little: "After He had removed [Saul], He raised up David to be their king, concerning whom He also testified and said, 'I HAVE FOUND DAVID the son of Jesse, A MAN AFTER MY HEART, who will do all My will.'
Here then is apostolic commentary on what it means to be a man after God's own heart: one who will do all His will. I emphasize the "all" because it was Saul's selective obedience that God considered disobedience. God longs for those who will do all His will, not just the parts they like.
Since David began as a man after God's own heart, but failed to remain such a man, there is both promise and warning in this passage.
The promise: we can be men & women whose hearts beat with God's. To be such requires whole-hearted obedience to His will we know.
The warning: we can cease to be men & women after God's own heart. When we deliberately choose our way over His way, we are headed Saul's way. David knew he had followed Saul's path through adultery and murder. That why he prayed so fervently, "take not your Holy Spirit from me." He had seen what happens when God's Spirit leaves.
The difference between Saul and David was not perfect performance. It was repentance. Saul was sorry, but not repentant. David, after confrontation, was both sorry and repentant.
Father, I want to be and live as a man after your heart. Grant me grace to do all your will, even the parts that are hard and painful. For Christ's sake, Amen.