In chapter 27, David flees to Gath, figuring that if he goes among the Philistines, Saul will not follow. Indeed, it is noted here that Saul gives up.
While in this area, he and his men make some raids, completely wiping out the Geshurites, Gezrites and Amalekites, because these apparently were among the people that God wanted wiped out back in the days of Joshua.
Why is David fighting Amalekites if Saul wiped them out already? Well, remember for one thing that Saul didn't wipe them out. As the SAB itself says, Saul's genocide of the Amalekites was "incomplete". For another thing, it's possible that this is another case of mistaken names, with more than one nation being known as "Amalekites".
Having destroyed all these people, David decides to lie to the king of Gath, and say that he was raiding his own people. The king buys it, and concludes that David will now be forced to be an ally of the Philistines forever.