how to write it  recursively

chaitu chaitu
chaitu chaitu used Ask the Experts™
on
how to construct the below HTML ;as you can see the table data can be multiply nested.

 while(rs.next())
		 {
			 
			 al.add(rs.getInt("ID"));
			 
			 Menu m = new Menu();
			 m.setId(rs.getInt("ID"));
			 m.setName(rs.getString("NAME"));
			 m.setMenuId(rs.getInt("PARENT_ID"));
			 
			 if(al.contains(rs.getInt("PARENT_ID")))
			 {
				 System.out.println("in if...................");
				 
				 ArrayList<SubMenu> subMenuList = new  ArrayList<SubMenu>();
				 SubMenu sm = new SubMenu();
				 sm.setId(rs.getInt("ID"));
				 sm.setName(rs.getString("NAME"));
				 sm.setMenuId(rs.getInt("PARENT_ID"));
				 subMenuList.add(sm);
				 m.setSubMenuList(subMenuList);
			 }
			 
			 System.out.println(m);
			 
		 }

Open in new window


    <li>
		   <a href="#" class="parent"><span>Menu 1</span></a>
				<div>
					<ul>
						<li><a href="#" ><span>Page 1</span></a></li>
						<li><a href="#" ><span>Page 2</span></a>
						
						<div>
				<ul>
					<li><a href="#" ><span>Page 4</span></a></li>
					<li><a href="#" ><span>Page 5</span></a></li>
				</ul>
					</div>
						</li>
					</ul>
				</div>
		</li>



		<li>
			<a href="#" class="parent"><span>Menu 2</span></a>
			<div>
				<ul>
					<li><a href="#" ><span>Page 3</span></a></li>
				</ul>
			</div>
		</li>


		 <li>
			 <a href="#" class="parent"><span>Help</span></a>
			 <div>
				<ul>
					<li><a href="#" ><span>About</span></a></li>
				</ul>
			</div>
		 </li>
 

Open in new window


this is the data from the table.
ID            NAME      PARENT_ID LINKS    ACTION
4	page1	1	/images/email.gif	page1
2	Menu2	(null)	(null)	                Menu2
1	Menu1	(null)	/images/home.gif	Menu1
3	Help	(null)	(null)	                Help
5	page2	1	(null)	                page2
6	page3	2	/images/photo.gif	page3
7	about	3	(null)	               about
8	page4	5	/images/photo.gif	page3
9	page5	5	(null)	               about

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
zzynxSr. Software engineer

Commented:
I would do it in two passes:
1. add all main menu items (parentID = NULL)
2. Add all others (order by parentID)

Author

Commented:
Please post the pseudo code.
Sr. Software engineer
Commented:
Something like this:

1.  for each main menu item:
Menu m = new Menu();
m.setId(rs.getInt("ID"));
m.setName(rs.getString("NAME"));
m.setSubMenuList(new  ArrayList<SubMenu>());

and store it in a Map<Integer, Menu>

2.
- for each entry,
     get the Menu out of the map based on the parentID
     from the Menu, get the submenu list and add a new submenu for this database entry
zzynxSr. Software engineer

Commented:
Thanx 4 axxepting

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial