It's mostly rote learning; you need to do it for all languages that have cases (I had to do it for Latin, for example). There are two phases:
Learn the tables by heart. There are not that many tables, and they are not that big, so a few days of studying should be enough (with plenty of recall afterwards). Don't learn the tables all at once, learn them one after another. This gives you a slow, but sure way to find the correct ending: just recite the table in your head. Whenever you write something and don't know the ending, use that method. When you forget a table, look it up and memorize it again.
The second phase is to use the correct ending without thinking. Like in sports, where you have to practice movements until you do them uncounsciously, this means practice, practice, practice. Eventually you'll do it. Until it works, use the first method if you are unsure. When you are writing a text, there's no excuse for using the wrong ending; you have the time to look it up. When you speak, mistakes are no problem.
You should also learn the vocabulary in the right way: Always learn the article together with the noun ("der Tisch", not "Tisch"). Always learn the complete verb pattern or patterns (often different patterns have different meanings): "jemandem (Dat) etwas (Akk) geben", not just "geben". Learners of English have to do the same, we need to learn "to put up with s.th." ("sich mit etwas abfinden") instead of just "put" (setzen, legen, stellen) etc. Finally, learn which case(s) belong to which prepositions.