Being after God’s own heart

After all that David had done in his life, his failures and despair.  How is it that he was still a man after God’s own heart?  What does that say for us when we fail?  How did David turn it around?