As a rule of thumb, you can say that the accusative case is used to mark the direct object, while the dative case marks the indirect object:
Sie fragt ihn.
sie "she", nominative
fragt "asks, is asking"
ihn "him", accusative (direct object)Sie gibt ihm den Schlüssel.
gibt "gives, is giving""
ihm "(to) him", dative (indirect object)
den Schlüssel "the key", accusative (direct object) This rule doesn't apply if certain prepositions are used:
Sie spricht mit ihm.
spricht "talks"
mit ihm "to him (lit. with him)", dative (!)
With locations, the accusative case tends to be used to describe a movement towards something, towards somewhere, into something etc.. The dative describes a "static" location or a movement out of somewhere or away from somewhere:
Sie fährt in die Stadt.
fährt "drives, is driving"
in die Stadt "(in)to the town", accusativeSie wohnt in der Stadt.
wohnt "lives, dwells"
in der Stadt "in the town", dativeSie kommt aus der Stadt.
kommt "comes, is coming"
aus der Stadt "out of the town", dativeI've just come across this website. Perhaps it's useful:
https://coerll.utexas.edu/gg/gr/cas_01.html