In the book of 1st Samuel we see that David endured trial after trial -- almost continuously. King David was an adulterer, a murderer, and he did not always act like a great representative of the Most High. Yet, God calls Him a "friend of God." When Saul disobeyed God's commands, the anointing placed on him when he was crowned king left. Our disobedience can & does separate us from the anointing that God has for our lives. As a follower of Christ, you have a ministry and a gift that you can only fulfill through Christ. But continuing to dabble in the things of the flesh can cause you to lose your anointing.
Another issue of importance is that God allowed all the things to come on David to test him and see if he could handle the throne. Could he obey God? Would he be different than Saul? Saul had a habit of half-obeying God's commands which is equivalent to disobeying God. But during David's affliction, he only praised and thanked God -- not understanding or knowing the purposes behind everything. The books of Samuel have to read in conjunction with Psalm because Psalm shows the agony David endured and the times He cried out to God. The common theme is that GOD ALWAYS DELIVERS. God is not going to test you without the deliverance already in place! The test is to keep the faith and endure. Paul says to "Count is as JOY" when we are tried. Because we know that this trying is necessary to show ourselves if we really believe what God has to say and are we willing to make a commitment to Him for now, for a while, or forever?
David was no perfect man BUT God was with him and knew his heart. God also punished him for his errors but David never esteemed himself better than God. The difference between Saul and David was their hearts -- not necessarily how they acted. David feared God -- even when he sinned and most importantly, David acknowledged and repented of sin. Saul did not.
In your tests in life, as a believer, it is paramount to stay in the Word so you will not lose faith. God will try you like gold in the fire! It's not fun, it's not always quick either. But should you pass -- you gain far more than you ever think you lost. The WORD says that He is the Deliverer of those who put their trust in Him; a Counselor; a Fortress; a Strong Tower.
David's kingdom was established with God forever...even Jesus Christ was a descendant of the line of David.