Well, let me take a stab at trying to answer your question(s):
1. What did the Police do wrong? Sounds like nothing. The encounter ended without you getting arrested, accosted, injured, and with a minor bit of inconvenience. Sounds like the police handled things fairly professionally on their part.
2. How could you beat an arrest for this? Well, it does not sound as if the police had any grounds to arrest you. If they had, it would depend on what you were charged with. Remember, being arrested does not mean you are guilty, it just means that the police had probable cause to have you arrested.
3. How about the way you handled it? Sounds like you handled it well. From your description, you were cooperative and compliant with the officers. Even though you did not want to give them your name, it did not hurt anything, and most jurisdictions have some sort of law that requires you to display ID when asked by the police under such circumstances. Refusal to do that would certainly not have helped anything.
4. What should you do differently. Well, make sure that you have a key, for one thing. And make sure that your current address is listed on your driver's license. To some extent, you have to consider the situation that the police faced. They were called to respond to suspicious activity, and found you sneaking around outside. They had no way to know whether you really lived there or not, or might have been involved with a domestic dispute with another occupant, and locked out on purpose.
Does that help?
The opinions expressed in this answer are meant for educational and public service purposes. Requesting general information about the law on a public website should never be a substitute for a personal consultation with an attorney who can give specific legal advice tailored to the facts of an individual case. Please be aware that Robert Hogan is licensed only in Texas and New Mexico, and that any opinions given are not meant to apply outside of these states. No attorney-client relationship is intended by answering questions or emails.