The Spirit of the LORD had left Saul and just as we read in the New Testament, when God’s Spirit leaves the demons will take up the place (Mt 12:43-45). It’s dangerous to have the Spirit of the Lord leave.
Of course there are questions that abound such as God really send the evil spirit? God doesn’t author evil but he is in control. He can remove protection where there once had been and permit demons to come in. This has the potential to be redemptive if that person would cry out to the Lord in repentance for relief. Especially if another person (i.e. David) comes in and worships (David’s main repertoire) and the harassing spirit leaves every time.
But be careful not to get so caught up in the question (although it’s ok to ask and ponder), yet miss the point. God was orchestrating a bigger picture where he was taking a lowly shepherd boy and placing him in the palace of the king. So that he himself would one day become king.
When the Spirit of the lord left and the demon spirit came, Saul was suffering. His servants suggested that he find a skillful musician to play the lyre when he was struggling in order to get relief. Someone remembered David and suggested him, calling him “a vailiant man, a warrior, eloquent, handsome, and the LORD is with him” (1 Sam 16:18).
So David was called up by King Saul to not play the lyre for Saul in his distress. David so impressed Saul that not only was David his personal musician, but he made him armor-bearer, the most trusted position in battle. At Saul’s request, Jesse released David from his family responsibilities to serve the king.
We see several interesting things here. With Saul we see that every time David played (and presumably worshiped the Lord), the spirit left Saul. If only Saul had seen the connection and repented, fearing the LORD greater than fearing man and trying to please him (1 Sam 15:24; 1 Sam 15:30), then maybe God would have restored his spiritual protection. I don’t think he would have remained as King, but perhaps he would have found relief from the demon and a place of rest again. Unfortunately that didn’t happen so we don’t know.
On David’s behalf, when he was anointed king, he didn’t just immediately go and try to take over. He want back to the field and tended the sheep. It was the LORD who raised David up in his own way.
When he needed to raise up Joseph to shepherd the foreign Egyptians and later save Israel, it was through the path of enslavement and then imprisonment to Pharaoh’s side. And now when the LORD wanted to raise up David to shepherd the people Israel, it was through the path of music. God uses many and strange paths to put people where he needs them to be in the hour they need to be there. But when God calls someone, he can put them in the place where they need to be.