Why was David's census so unpleasant to our Creator? Was it a sin? If so, why? What is wrong in doing a census? There were previous censuses made and there were no problems.
Rashi to Exodus 30:12 explains that counting Jews directly incites the Evil Eye, which, in turn, causes a plague.
ולא יהיה בהם נגף. שֶׁהַמִּנְיָן שׁוֹלֵט בּוֹ עַיִן הָרָע, וְהַדֶּבֶר בָּא עֲלֵיהֶם, כְּמוֹ שֶׁמָּצִינוּ בִימֵי דָּוִד (שמואל ב כ"ד):
”That there not be calamity among them” - for the Evil Eye rules through counting, and a plague comes upon them, like we find in the days of David (Shmuel 2:24:1ff).
Unlike the census in the days of King David, the previous ones were done through half-Shekalim, as prescribed in the Exodus passage. That way, it was the coins being counted, not the people, and so the Evil Eye would not rule over them.