David was nowhere near the battlefield where King Saul and his sons died in battle. News reached David days later by an Amalekite who admitted to striking a deathblow on Saul, for which David executed him.
King Saul was so distracted by his hatred for David that he neglected his duties as King, leaving Israel ill prepared to face the Philistine invasion. Saul and his sons perished in battle, finally ending the era of Saul.
David joins the Philistines forces that are mustering to battle King Saul but is sent home, his loyalties being questionable. Upon their return to Ziklag they find their families stolen by Amalekites, give chase and prevail.
David is still amongst the Philistines as they gather for war against King Saul. This war brought dread to Saul and in desperation for spiritual help, he goes to a witch for a séance. There he is told God is his enemy.
David gave up on God delivering him from Saul as long as he remained in Saul’s territory. So he fled to a less hostile enemy, to ally himself there (in appearance), secretly raiding other enemies of Israel to survive.