过滤将ArrayList <object>添加到HashMap </object>

时间:2014-01-21 16:12:10

标签: java android arraylist hashmap

我有一个ArrayList,它的层次结构有3个级别。类别,论坛,ChildForum。 但是Forum和ChildForum,它们具有相同的属性(最重要的属性是nodeId和parentNodeId)。而且coupe论坛里面没有任何ChildForum。

Category------
             |
            Forum---------
             |           |
             |        ChildForum--------
             |                         |
             |______________________Thread

所以我想找到一种方法将它们绑定到listviews和onClickItem,查看哪个论坛有孩子,这样我就可以将视图导航到正确的片段

这就是我现在所做的:

    nodeList = new ArrayList<Node>(); //nodeList contains Category, Forum, and ChildForum
    forumNodeList = new ArrayList<Node>(); 
    childList = new ArrayList<Node>(); // temp array
    forumChildNodeList = new HashMap<String, ArrayList<Node>>();

填写数据

for (int i = 0; i < nodeList.size(); i++) {
            if (nodeList.get(i).getParent_node_id().equals(nodeId)) { //nodeId = categoryId
                forumNodeList.add(nodeList.get(i));
            }

            for (int j = 0; j < forumNodeList.size(); j++) {
                if (forumNodeList.get(j).getNodeId()
                        .equals(nodeList.get(i).getParent_node_id())) {                     
                    childList.add(nodeList.get(i));
                    // Log.d("childList", "" + childList.size());
                    forumChildNodeList.put(
                            forumNodeList.get(j).getNodeId(), childList);
                }
                forumChildNodeList.put(forumNodeList.get(j).getNodeId(),
                        childList);
            }
        }

setOnClickItem:

getListView().setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> arg0, View arg1,
                int position, long arg3) {
            if (forumChildNodeList.get(
                    forumNodeList.get(position).getNodeId()).size() > 0) {

                //Fragment Transaction to ChildForumFragment
            } else {

                //Fragment Transaction to ThreadFragment
            }

        }
    });

当我显示登录onClick时。看起来所有具有论坛ID的HashMap都具有相同的ChildForum。事实上,其中一些没有任何childForum。 我肯定知道For循环和if条件有问题。或者我错过了什么?请帮忙! 提前谢谢!

1 个答案:

答案 0 :(得分:0)

我发现了我的问题。这是条件问题:

getListView().setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> arg0, View arg1,
            int position, long arg3) {
        if (forumChildNodeList.get(forumNodeList.get(position)
                    .getNodeId()) != null) {

            //Fragment Transaction to ChildForumFragment
        } else {

            //Fragment Transaction to ThreadFragment
        }

    }
});

数组应该是 ArrayList!= null 而不是 ArrayList.size()&gt; 0