According to 1 Kings 15:5, David was a righteous man, who did (almost) everything God told him:
On the other hand, 2 Samuel 24:10 records a major sin of David, for which he is later punished harshly:
I don't really see the problem. The verse in Kings doesn't exactly say David never sinned; it just says he did everything God told him to, with one exception. I suppose, in a sense, God tells us all not to sin, but this is a rather weak sense. To really establish a contradiction, we'd need a verse where God explicitly says "do X" and David doesn't (perhaps there is such a verse, but I haven't looked).