God was fully aware of David's problems. David felt like he was stuck in prison with no end to the risk of being caught. David no doubt experienced a myriad of emotions of which great fear has seemingly enveloped his human heart. He does the right thing and turns to God in prayer. All David knew is that God understands the pain he was going through at that time.
We too must come to the place where we give our problems to God and say, "Whatever happens in this situation is Your business not mine. I'll keep making the best decisions possible, but the results are Your business because I belong to You and I trust that You know what is best for my life."
The last part of the Psalm says, "the righteous shall compass me about; for thou shalt deal bountifully with me." Thankfully, these words indicate at least of glimmer of hope from David as he acnowledges that while still stuck in a cave, he realizes that one day he will be gathered around other people that also trust in God.
Practically, we must ponder the setting. Did David know at this point he would be the next king of Israel? I doubt it. Did David know for sure he would get out of that cave alive? I doubt it. All he knew is that God knows all things and He is well aware of the predicament he was in at the moment. Notice that God never prevented David from being in that cave in the first place. God promises to guide us through our issues. He never promises that we avoid problems in the first place.
This leads us back to the verse ending. David is saying in effect, "I could die here and end up with other believers in heaven. Or God could rescue me through this situation and then, before I know it, I could be gathered with other believers praising His name. Either way, I will be with other believers praising Him and that is a good thing. Therefore, whatever happens to me is God's problem because He knows all things and He already knows the outcome of this situation. I (David) won't give up, but at the same time, I trust that whatever happens, is His problem. I will end up praising Him no matter what is the outcome of what I am dealing with at this moment."