How to create nested comments in Java / Android

Threading comments is a good way to make a conversation easy to read

Comments, for better or worse, are everywhere. There is a lot to dislike with comments (don’t get me started on the actual things being said) but they can be effective for conversation, especially with the addition of threaded / nested comments.

Where forums are generally one giant linear conversation, threaded comments add more context to the conversation by placing the response under the comment it was intended to be directed at. You’re probably so used to seeing comments this way that you don’t even think about it, but how about implementing this functionality?

To produce a nested comment thread, you first need the comment system to be capable of referring a comment to the ID of a parent comment. This is pretty standard so you likely have that already. Now let’s assume you want to bring the comment data into a mobile application via an API and you want to thread the conversation.

The following is an implementation in Java for an Android application, but the logic would apply to any language.

Your definition of a Comment object will be different than mine so I left that class out intentionally. The resulting list of comments will ordered based on depth so that a parent comment will be followed by its child comments. Each Comment object will also have a property populated holding that comment’s depth level and child count.

Using those properties you’ll be able to set the display of the comments in a threaded fashion by detecting which comments have children and indenting or styling based on depth level. For instance, if the comment has a parentID, you know it’s a child comment and can apply a style. Once you know it’s a child comment you can indent it by multiplying the commentDepth by some number of pixels.

ITWorld DealPost: The best in tech deals and discounts.
Shop Tech Products at Amazon