In chapter twenty-nine David was sovereignly kept away by God from joining the Philistines' camp to fight against Israel. The lords of the Philistines refused to have David go with them into battle against Israel, and Achish therefore sent him away (vv. 6-11).
If David had fought against Israel, he would have had a bad name for the rest of his life. David, however, was not involved in the destruction of Saul, his sons (including Jonathan), and the men of Israel (31:1-6).
Under God's sovereignty David was kept from joining the camp of the Philistines so that David could rescue his two wives and the families of his men, who had been captured by the Amalekites (30:18-20).
Under God's sovereignty, David saved himself from the turmoil of his men in losing their families to the Amalekites (30:1-6a).
Finally, as a result of being sovereignly kept by God from joining the Philistines' camp to fight against Israel, David, after defeating the Amalekites, sent some of his spoil as presents to his friends and friends of his men in many cities (vv. 26-31).