David saved Keilah (men of his own tribe) from the Philistines, but then found himself, with his men, in a walled town. To Saul this was a splendid opportunity to capture or kill David — it was so much easier than hunting him in the open wilderness. And the men of Keilah, mindful of what had happened at Nob (1Sa 22:18,19), were disposed to seek Saul’s friendship by betraying David to him (1Sa 23:7). Divine counsel by Urim and Thummim saved the situation (vv 9-12). David had no desire to be encircled, because the last thing he wanted was to have to fight against “the Lord’s anointed“. And so (directed by divine counsel?) he cleared out.
What helps to explain the attitude of the men of Keilah is the fact that they were Calebites, as also were the men of Ziph (1Ch 4:16,19). Their disreputable link with Nabal (see 1Sa 25) evidently counted for more than their honorable descent from the courageous and faithful Caleb. The men of Ziph likewise attempted a betrayal (1Sa 23:19); had it not been for the providence of God (1Sa 23:27) they would have succeeded.