You've learned that some prepositions always trigger Akkusativ (durch, für, ohne...) and others always trigger Dativ (mit, bei, von...). But there's a special group of nine very common prepositions used to describe location — in, an, auf, über, unter, vor, hinter, neben, zwischen — that don't belong permanently to either case. They swing between Akkusativ and Dativ depending on the meaning of the sentence, which is why German calls them Wechselpräpositionen, "switching prepositions."
The golden rule that settles the choice every time is to ask yourself a question before building the sentence: if the sentence describes movement or a transition from one place to another — so that you could ask Wohin? ("to where?") — use Akkusativ. If the sentence describes a fixed position or a state of rest in a location — so that you could ask Wo? ("where?") — use Dativ.
Compare these two sentences: Ich lege das Buch auf den Tisch (I put the book on the table; this is movement — the book moves from my hand onto the table, so we ask Wohin? and use Akkusativ den). Versus: Das Buch liegt auf dem Tisch (the book is lying on the table; this describes a fixed state with no movement, so we ask Wo? and use Dativ dem).
Here's something that helps a lot: there are verb pairs tied directly to this distinction. legen (to lay something down flat — a motion verb) pairs with liegen (to lie/be lying — a state-of-rest verb), and stellen (to stand something up — a motion verb) pairs with stehen (to stand/be standing — a state-of-rest verb). Motion verbs usually call for Akkusativ; state-of-rest verbs call for Dativ.
Many learners come from a language where the preposition and the following noun don't change form depending on whether the verb expresses motion or rest — "I put the book on the table" and "the book is on the table" use the exact same preposition with no grammatical shift at all. Because nothing in their native grammar prepares them for this, the Wechselpräpositionen distinction is often one of the most confusing points to master.
A common mistake is defaulting to Dativ with all nine of these prepositions, since learners often meet the fixed Dativ prepositions first, producing the wrong Ich gehe in dem Park instead of the correct Ich gehe in den Park when describing going into the park (motion). Always ask Wohin or Wo before choosing the case.